我将JWT用于RESTful API(用于移动设备的Laravel Web服务)。如何将令牌过期设置为永不过期,或者如何设置令牌过期的最佳实践?因为当前我需要在令牌过期时每次都获取令牌,所以任何人都可以遇到此问题或令牌过期的最佳解决方案。
没有什么可以使令牌永不过期的。但是,您可以将有效期延长到非常长的时间范围,例如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年的时间可以刷新它。当用户下次打开应用程序并验证令牌时,可以刷新它。您可以刷新令牌,如文档中提到这里。我也建议您通过这个laracasts讨论。
另外,我在StackOverflow上发现了这个问题,我认为这会有所帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句