繁体   English   中英

无法在 Tymon JWT 中添加自定义声明

[英]Unable to add custom claim in Tymon JWT

我正在使用Tymon JWT在 Laravel 中生成我的令牌。 我仔细按照Tymon 的 github 站点中的指南添加了我的自定义声明,如下所示:

$customClaims = ['foo' => 'bar', 'baz' => 'bob'];
JWTAuth::attempt($credentials, $customClaims);

在对用户进行身份验证后,我设法生成了一个令牌,但是当我使用 JWT 解码器对令牌进行解码时,我只能看到默认声明,而看不到我的自定义声明。

您正在使用Tymon JWT 1.0.0版吗?

从Github Tymon JWT

对于版本0.5。*有关文档,请参阅WIKI

1.0.0的文档即将发布,但此处未完成的指南

使用

JWTAuth::customClaims(['foo' => 'bar'])->attempt(['login' => '', 'password' => '']);

您可以使用:

$store = [
    'id'    => 1,
    'name'  => 'Store1'
];

$token = JWTAuth::customClaims(['store' => $store])->fromUser($user);

并获取信息:

$storeData = JWTAuth::getPayload()->get('store');

通过将getJWTCustomClaims方法放在我的JWTSubject上,我能够添加自定义声明。

示例:如果要为用户类指定防护并将该信息放入令牌中,请执行以下操作:

use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements JWTSubject
{
    /**
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [
            'guard' => 'admins', // my custom claim, add as many as you like
        ];
    }
}

请注意不要添加太多自定义声明,因为它们会增加令牌的大小。

这是我使用的Tymon-jwt的版本: “ tymon / jwt-auth”:“ dev-develop#f72b8eb as 1.0.0-rc.3.2”

希望这可以帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM