phplaravellaravel-passport

How to invalidate all tokens for an user in laravel passport?


In our app when user logs out we invalidate the access token for that particular device this way.

$user = $request->user();

$value = $request->bearerToken();
$id = (new Parser())->parse($value)->getHeader('jti');
$token = $user->tokens->find($id);
$token->revoke();

But when an user deactivates his/her account, we would like to invalidate all the access tokens from all the devices the user is logged in. I looked through the document but did not find anything useful. Thanks


Solution

  • Take a look at the HasApiTokens trait provided by passport. The documentation recommends adding this trait to your User model. One of the methods it provides is tokens(), which defines a hasMany relationship between Laravel\Passport\Token and models using the trait. You can use this to retrieve a list of all of the tokens for a given user:

    $userTokens = $userInstance->tokens;
    

    The token model itself has a revoke method:

    foreach($userTokens as $token) {
        $token->revoke();   
    }