RESTful API 使用 JWT(JSON Web 令牌)设置令牌过期

RESTful API using JWT (JSON Web Token) setup token expiry

我将 JWT 用于 RESTful API(Laravel 移动网络服务)。如何将令牌过期设置为永不过期或设置令牌过期的最佳做法是什么? 因为目前每次令牌过期时我都需要获取令牌,任何人都可以遇到这个问题或令牌过期的最佳解决方案。

没有什么可以使令牌永不过期。但是,您可以将到期日期延长到非常长的时间跨度,例如 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. I would recommend going through this laracasts discussion 中所述。

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