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

怎甘沉沦 提交于 2019-12-31 18:58:52

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/42851676/how-to-invalidate-all-tokens-for-an-user-in-laravel-passport

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!