【问题标题】:How to add custom data to Laravel Passport API token?如何将自定义数据添加到 Laravel Passport API 令牌?
【发布时间】:2021-03-03 20:52:41
【问题描述】:

我正在使用 Laravel Passport,我想知道是否可以将自定义数据添加到 Laravel\Passport\Token

//This is how I create the token
$user = $request->user();
$token = $user->createToken('ACCESS_TOKEN')->accessToken;

我将令牌发送到带有标头 Authorization: Bearer ${token} 的 API

有什么方法可以将自定义信息添加到令牌中?像这样的:

$token->customField = 'custom value';
$value = $request->user()->token()->customField;

我已阅读Passport Docs,但没有相关信息。

【问题讨论】:

    标签: php laravel jwt laravel-passport


    【解决方案1】:

    不,Passport 默认不支持此功能,but it has been requested

    JWT 使用自定义声明支持自定义数据。 Passport 不提供向 JWT 添加自定义声明的功能,但看起来有人制作了一个包来添加该功能:https://github.com/corbosman/laravel-passport-claims

    快速浏览一下,您似乎可以向 JWT 添加自定义声明,但我没有看到任何帮助程序或任何用于读取该数据的东西。您必须自己解析令牌并获取声明:

    $jwtParser = app()->make(\Lcobucci\JWT\Parser::class);
    $claimValue = $jwtParser->parse('your-bearer-token')->getClaim('your-claim-name');
    

    注意:我自己从来没有做过这个,我从来没有使用过那个包,这里的所有东西都未经测试。

    【讨论】:

      【解决方案2】:

      您可以通过使用自定义字段创建迁移文件来手动添加它。

      public function up()
      {
          Schema::table('oauth_access_tokens', function (Blueprint $table) {
              $table->string('customField',20)->after('client_id')->nullable();
          });
          
      }
      

      tokenCreate() 之后将字段值添加到表中:

      $token = $user->createToken($user->email);
      DB::table('oauth_access_tokens')
                 ->where('id', $token->token->id)
                 ->update(['customField' => $request->customField]);
      

      【讨论】:

        猜你喜欢
        • 2020-01-15
        • 2018-03-24
        • 2019-03-08
        • 2018-01-11
        • 2019-08-30
        • 2019-01-28
        • 1970-01-01
        • 2023-03-15
        • 1970-01-01
        相关资源
        最近更新 更多