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

Sayantan Das picture Sayantan Das · Mar 17, 2017 · Viewed 20.2k times · Source

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

Answer

Jeff Lambert picture Jeff Lambert · Mar 17, 2017

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();   
}