【问题标题】:Unable to add custom claim in Tymon JWT无法在 Tymon JWT 中添加自定义声明
【发布时间】:2017-05-25 03:08:09
【问题描述】:

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

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

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

【问题讨论】:

  • 你试过var_dumpJWTAuth::attempt的结果了吗?

标签: php laravel jwt


【解决方案1】:

您可能正在使用 Tymon JWT 1.0.0 版?

来自 Github Tymon JWT

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

1.0.0 的文档即将推出,但有一个未完成的指南here

使用

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

【讨论】:

【解决方案2】:

您可以使用:

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

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

并获取信息:

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

【讨论】:

    【解决方案3】:

    我可以通过将 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"

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2018-07-05
      • 2019-02-26
      • 1970-01-01
      • 2021-07-20
      • 1970-01-01
      • 2020-03-15
      • 2016-01-06
      • 2023-04-10
      • 2021-04-03
      相关资源
      最近更新 更多