Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 630
Sayantan Das Avatar asked Mar 17 '17 07:03

Sayantan Das


People also ask

How can I cancel my Laravel Passport token?

You may revoke a token by using the revokeAccessToken method on the Laravel\Passport\TokenRepository .

How can I check my Passport token is valid or not in Laravel?

If you don't want to use the Passport middleware in the project where you want to validate the tokens, you would have to create an endpoint in the Laravel Passport server that can accept the token, perform the usual Passport validation and return a response to your service.

What is difference between JWT and Passport Laravel?

The "tymondesigns/jwt-auth" is a PHP Laravel implementation of the JWT protocol. On the other hand, Passport also uses JWT by default plus a huge extra, a complete Oauth2 implementation. Regarding the functionality, as I said they both use JWT thus you can use whichever you like to authentication via tokens.

How do I remove refresh token?

To revoke a refresh token, send a POST request to https://YOUR_DOMAIN/oauth/revoke . The /oauth/revoke endpoint revokes the entire grant, not just a specific token. Use the /api/v2/device-credentials endpoint to revoke refresh tokens.


2 Answers

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();    } 
like image 193
Jeff Lambert Avatar answered Sep 20 '22 07:09

Jeff Lambert


This worked for ME:

use Laravel\Passport\Token;   Token::where('user_id', $user->id)                 ->update(['revoked' => true]); 
like image 27
Ray Zion Avatar answered Sep 23 '22 07:09

Ray Zion