36

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

Sayantan Das
  • 1,619
  • 4
  • 24
  • 43

2 Answers2

70

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();   
}
Jeff Lambert
  • 24,395
  • 4
  • 69
  • 96
  • 1
    We Manually set the revoke field to 1 in the oauth_access_tokens table for a user id. But this seems better – Sayantan Das Mar 18 '17 at 02:22
  • 3
    I manually revoke all previous token of a user but "oauth_refresh_tokens" table still have the entry with revoked "0" value. However "oauth_access_tokens" table is updated with value "1" for revoked. Can you help me this situation or should I not need to worry about this? – Sachin Kumar Apr 21 '18 at 11:12
  • 1
    Thanks it work like charm for me. you are super duper guy. – Denis Bhojvani Jan 03 '19 at 13:34
2

This worked for ME:

use Laravel\Passport\Token;

 Token::where('user_id', $user->id)
                ->update(['revoked' => true]);
Ray Zion
  • 610
  • 10
  • 11