laravel 如何使laravel护照中的用户的所有令牌无效?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42851676/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to invalidate all tokens for an user in laravel passport?
提问by Sayantan Das
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
但是当用户停用他/她的帐户时,我们希望使用户登录的所有设备的所有访问令牌无效。我查看了文档但没有找到任何有用的信息。谢谢
回答by Jeff Lambert
Take a look at the HasApiTokens
trait provided by passport. The documentationrecommends 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:
看看HasApiTokens
护照提供的特征。该文档建议将此特征添加到您的用户模型中。它提供的方法之一是tokens()
,它定义了使用 trait 的模型hasMany
之间的关系Laravel\Passport\Token
。您可以使用它来检索给定用户的所有令牌的列表:
$userTokens = $userInstance->tokens;
The token model itself has a revoke
method:
令牌模型本身有一个revoke
方法:
foreach($userTokens as $token) {
$token->revoke();
}