我正在将 JWT 用于 RESTful API(适用于移动设备的 Laravel Web 服务)。如何将 token 过期设置为永不过期,或者设置 token 过期的最佳实践是什么? 因为目前我每次 token 过期时都需要获取 token ,任何人都可以遇到这个问题或 token 过期的最佳解决方案。
最佳答案
没有什么可以使 token 永不过期。但是,您可以将到期日期延长到非常大的时间跨度,例如 1 年。这是可能的,但出于安全考虑,不建议这样做。
为了实现这一点,您需要配置两部分, token 刷新时间和 token 到期时间。
所以在config/jwt.php
'refresh_ttl' => 29030400, // Number of minutes in 1 year (12*4*7*24*60*60)
当您创建 token 时,您可以传递类似以下内容
$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
]
];
现在,您的 token 在 1 年内永远不会过期。并且您有长达 1 年的时间来刷新它。当用户下次打开应用程序并且您对 token 进行身份验证时,您可以刷新它。您可以刷新 token ,如文档 here 中所述。 。我建议您浏览一下 laracasts discussion也是如此。
另外,我发现了这个question在 StackOverflow 上,我认为这会有所帮助。
关于api - 使用 JWT(JSON Web token )设置 token 过期的 RESTful API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33564887/