devondahon's avatar

Laravel Passport: How to revoke and delete refresh token?

I'm using this to delete a user access token:

$request->user()->token()->delete();

But the refresh token associated is still in the database, can I revoke it and/or delete in a similar way ?

And subsidiary question: How can I see the available methods in $request->user() and in $request->user()->token() with vscode ?

I'm currently using:

    Log::info(get_class($request->user()));
    Log::info(get_class_methods('App\Models\User'));
    Log::info(get_class($request->user()->token()));
    Log::info(get_class_methods('Laravel\Passport\Token'));

But there may be a better to show it.

0 likes
4 replies
mwguerra's avatar
mwguerra
Best Answer
Level 27

The HasApiTokens trait you have in your User model has those methods.

The best way I found to revoke both the access token and the refresh token was to call the methods revokeAccessToken and revokeRefreshTokensByAccessTokenId from the Passport repositories. You can find the original code in the Passport documentation.

Here is an example LogoutController I did some time ago. Hope it helps!

public function __invoke(Request $request)
{
    $request->user()
        ->tokens
        ->each(function ($token, $key) {
            $this->revokeAccessAndRefreshTokens($token->id);
        });

    return response()->json('Logged out successfully', 200);
}

protected function revokeAccessAndRefreshTokens($tokenId) {
    $tokenRepository = app('Laravel\Passport\TokenRepository');
    $refreshTokenRepository = app('Laravel\Passport\RefreshTokenRepository');

    $tokenRepository->revokeAccessToken($tokenId);
    $refreshTokenRepository->revokeRefreshTokensByAccessTokenId($tokenId);
}

Regarding the VSCode, have a look into the PHP Intelephense and the Laravel IDE Helper extensions.

6 likes
devondahon's avatar

@mwguerra Thanks for your answer!

I'm finally using this in my logout route:

    // Revoke access token
    // => Set public.oauth_access_tokens.revoked to TRUE (t)
    $request->user()->token()->revoke();

    // Revoke all of the token's refresh tokens
    // => Set public.oauth_refresh_tokens.revoked to TRUE (t)
    $refreshTokenRepository = app('Laravel\Passport\RefreshTokenRepository');
    $refreshTokenRepository->revokeRefreshTokensByAccessTokenId($request->user()->token()->id);

Please or to participate in this conversation.