【问题标题】:How to add custom claims to laravel-passport Access token?如何向 laravel-passport 访问令牌添加自定义声明?
【发布时间】:2020-01-15 21:01:41
【问题描述】:

我刚刚使用了laravel-passport,它和jwt auth一样。

我想向我的 accessToken 添加一些自定义声明,可以吗??

我想在访问令牌和 API 调用中传递 2fa_status => true 有了这个访问令牌,我还想要令牌的声明。

例如预期的令牌声明

{
  "aud": "7",
  "jti": "123",
  "iat": 1568368682,
  "nbf": 1568368682,
  "exp": 1599991082,
  "sub": "2",
  "scopes": [],
  "2fa_status": false
}

我正在生成令牌如下:

  $tokenResult = $user->createToken('Personal Access Token');

【问题讨论】:

  • 你能解释一下为什么需要自定义声明吗?
  • 例如在令牌中我想传递它是成员或用户的令牌。我有两个单独的警卫。谢谢
  • 我已经更新了我的问题,请再次查看。

标签: laravel laravel-passport


【解决方案1】:

我处于类似情况,但我在身份验证期间使用密码授予客户端向用户颁发令牌,我需要使用个人访问令牌为用户生成访问令牌,以便他们自己在他们的第 3 方应用程序中使用.您可以通过更新范围来解决问题。如果 2fa 已通过,我还需要验证用户。

在你的

AuthServiceProvider.php

    public function boot()
    {
        $this->registerPolicies();

        Passport::routes(function ($router) {
            $router->forAccessTokens();
            $router->forPersonalAccessTokens();
            $router->forTransientTokens(); // register the transient token. skip if all routes are enabled
        });

        // Add scope to verify the user
        // take note that here 2 scope for this due to refresh token scope
        Passport::tokensCan([
            '2fa-pass' => '2FA Pass',
            '2fa-not-pass' => '2FA Pass',
        ]);
    }

下一步是在您发送密码授权类型的身份验证过程中

  // I'm using route::dispatch to do a proxy request
  // you can use Guzzle if you want
  $request->request->add([
    'grant_type' => 'password',
    'client_id' => 'client-id',
     client_secret' => 'client-secret',
    'username' => $credentials['email'],
    'password' => $credentials['password'],
    'scope' => '2fa-not-pass 2fa-pass' // take note that I added the two scope here
  ]);

  $tokenRequest = Request::create('/oauth/token', 'POST');

  $response = \Route::dispatch($tokenRequest);

然后在您的 2FA 验证过程中


   // your process of verifying the 2FA code

   // after that you need to update the scope by doing a refresh token
   $request->request->add([
     'grant_type' => 'refresh_token',
     'refresh_token' => $request->input('refresh_token'),
     'client_id' => 'client-id',
     'client_secret' => 'client-secret',
     'scope' => '2fa-pass' // I removed the 2fa-not-pass in refreshing the token
    ]);

  $tokenRequest = Request::create('/oauth/token', 'POST');

  $response = \Route::dispatch($tokenRequest);

注意范围,刷新令牌时,只能获得与原始访问令牌相同或更窄的范围。如果您尝试获取原始访问令牌未提供的范围,则会收到错误消息。 - 帕特里克斯

在这里回答:https://stackoverflow.com/a/45856634/11537130

请注意,这将生成一个具有新范围的新令牌

【讨论】:

    【解决方案2】:

    认为您可以做的事情与以下问题的答案非常相似: Customising token response Laravel Passport

    在您自己的 BearerTokenResponse 类中,重写 generateHttpResponse 方法,在其中您可以在将访问令牌转换为 JWT 之前添加任何内容:

        public function generateHttpResponse(ResponseInterface $response)
        {
            $expireDateTime = $this->accessToken->getExpiryDateTime()->getTimestamp();
    
            // add custom claims here, ie. $this->accessToken->withClaim('name', 'value');
    
            $jwtAccessToken = $this->accessToken->convertToJWT($this->privateKey);
    
            ...
    

    【讨论】:

      【解决方案3】:

      有可能

      将此添加到AuthServiceProvider

      Passport::routes();
      Passport::personalAccessClientId(1); //<-- this 1 is id of your personal key
      Passport::tokensExpireIn(now()->addDays(15));
      Passport::refreshTokensExpireIn(now()->addDays(30));
      

      现在您可以像这样创建新令牌

      $user->createToken('email')->accessToken; // you can change email to any for remember why this code generated like social facebook
      

      根据documents 添加更多参数试试这个

      $user->createToken('email', ['extra' => 'params'])->accessToken;
      

      希望对你有帮助

      【讨论】:

      • 谢谢,但我不想创建新的令牌我已经生成了一个令牌,我想在其中添加一些自定义属性。
      • @VishalRibdiya 检查我在回答中添加了$user-&gt;createToken('email', ['extra' =&gt; 'params'])-&gt;accessToken;
      • 我认为存在一些沟通障碍,我已经更新了我的问题,请再次检查,如果您能提供帮助,请告诉我。谢谢
      • $user-&gt;createToken('email', ['extra' =&gt; 'params']) 这不起作用,因为第二个参数是 SCOPES 而不是额外的参数。
      • 它会返回错误The requested scope is invalid, unknown, or malformed
      猜你喜欢
      • 2021-12-01
      • 2019-06-24
      • 2021-11-14
      • 2019-11-14
      • 2017-11-29
      • 1970-01-01
      • 2017-05-14
      • 2021-03-03
      • 1970-01-01
      相关资源
      最近更新 更多