Laravel Passport API:检索经过身份验证的令牌

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46673667/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:47:08  来源:igfitidea点击:

Laravel Passport API: Retrieve Authenticated Token

phplaravelapitokenlaravel-passport

提问by Paul Hermans

Situation

情况

I'm using Laravel Passport API to communicate between Laravel and external "agents" via Personal Access Tokens: https://laravel.com/docs/5.5/passport#personal-access-tokens

我正在使用 Laravel Passport API 通过个人访问令牌在 Laravel 和外部“代理”之间进行通信:https://laravel.com/docs/5.5/passport#personal-access-tokens

You can create multiple tokens per user.

您可以为每个用户创建多个令牌。

Authentication works and I can retrieve the User via Auth::User()

身份验证有效,我可以通过以下方式检索用户 Auth::User()

Question

How can I check which token is used?

如何检查使用了哪个令牌?

Background

背景

I want to use different tokens for different "agents" for the same user and I need to know which token is used to see who is connecting.

我想为同一用户的不同“代理”使用不同的令牌,我需要知道使用哪个令牌来查看谁在连接。

回答by ElChupacabra

You can use:

您可以使用:

Auth::user()->token()

function to get token model. This is object of class "Token extends Model" so you should be able to use it like any other model.

获取令牌模型的函数。这是“令牌扩展模型”类的对象,因此您应该能够像使用任何其他模型一样使用它。

In addition in my project I also have that model:

此外,在我的项目中,我也有该模型:

namespace App;

use Illuminate\Database\Eloquent\Model;

class OauthAccessToken extends Model
{
    //
}

and relation:

和关系:

class User extends Authenticatable
{
    //...
    public function accessTokens()
    {
        return $this->hasMany('App\OauthAccessToken');
    }
}

So I can simply access all tokens and for example delete them:

所以我可以简单地访问所有令牌,例如删除它们:

Auth::user()->accessTokens()->delete();