【问题标题】:RESTful API using JWT (JSON Web Token) setup token expiry使用 JWT(JSON Web 令牌)设置令牌到期的 RESTful API
【发布时间】:2016-02-07 11:42:12
【问题描述】:

我将 JWT 用于 RESTful API(Laravel Web-Services for mobile)。如何将令牌到期设置为永不过期或设置令牌到期的最佳实践是什么? 因为目前我每次令牌过期时都需要获取令牌,任何人都可以遇到这个问题或令牌过期的最佳解决方案。

【问题讨论】:

  • 您能否提供更多详细信息,例如,您是否使用 Angular.js,用例是什么?
  • 我没有使用 Angular.js,只是 Jwt-auth 用于 restful-api。我只想要处理令牌到期时间的标准方法。因为我的服务是为移动用户创建的。

标签: api laravel-5 token jwt restful-architecture


【解决方案1】:

没有什么可以使令牌永不过期。但是,您可以将到期日期延长到一个非常长的时间跨度,例如 1 年。这是可能的,但出于安全考虑,不建议这样做。

为了实现这一点,您需要配置两个部分,令牌刷新时间和令牌到期时间。

所以在config/jwt.php

'refresh_ttl' => 29030400,  // Number of minutes in 1 year (12*4*7*24*60*60)

当您创建令牌时,您可以传递如下内容

$tokenId    = base64_encode(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
$issuedAt   = Carbon::now()->timestamp;
$notBefore  = $issuedAt;             //Adding 10 seconds
$expire     = $notBefore + 12*4*7*24*60*60;            // Adding 6 hours
    /*
    * Create the token as an array
    */
    $data = [
      'iat'  => $issuedAt,      // Issued at: time when the token was generated
      'jti'  => $tokenId,   // Json Token Id: an unique identifier for the token
      'iss'  => 'https://example.com',       // Issuer
      'nbf'  => $notBefore,        // Not before
      'exp'  => $expire,           // Expire
      'data' => [                  // Data related to the signed user
      'userId'   => Auth::user()->id, // userid from the users table
      ]
    ];

现在,您的令牌将在 1 年之前永不过期。你有长达 1 年的时间来刷新它。当用户下次打开应用程序并且您对令牌进行身份验证时,您可以刷新它。您可以刷新令牌,如文档 here 中所述。我建议也通过这个 laracasts discussion

另外,我在 StackOverflow 上找到了这个 question,我认为它会有所帮助。

【讨论】:

  • 我可以在 Authenticacontroller 的 Web 服务中自定义令牌过期消息,就像我想在数组中显示消息,成功 =0 和 msg = 令牌过期,请重新登录
猜你喜欢
  • 2016-08-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-01
  • 1970-01-01
  • 2015-06-22
  • 2017-08-20
  • 2016-01-02
  • 2018-06-11
相关资源
最近更新 更多