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

时间:2015-11-06 10:38:32

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

我正在使用JWT for RESTful API(Laravel Web-Services for mobile)。如何设置令牌到期永不过期或设置令牌到期的最佳做法是什么? 因为目前我需要在令牌过期时每次都获得令牌,任何人都可以拥有此问题或令牌到期的最佳解决方案。

1 个答案:

答案 0 :(得分:2)

没有任何东西可以使令牌永不过期。但是,您可以将到期日期延长到非常大的时间跨度,例如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,我认为这会有所帮助。