Node.js - Express.js JWT,如何检查令牌是否过期?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34329280/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node.js - Express.js JWT, how to check token expired or not?
提问by Karthik
how to check whether my token is expired or not?
如何检查我的令牌是否已过期?
var token = jwt.sign(user,app.get('superSecret'),{
expiresIn : 2
});
回答by Andre Kreienbring
I assume you are using the jsonwebtoken package that is documented here
我假设您正在使用此处记录的 jsonwebtoken 包
If that is the case, have a look at the jwt.verifymethod:
如果是这种情况,请查看jwt.verify方法:
jwt.verify(token, 'shhhhh', function(err, decoded) {
if (err) {
/*
err = {
name: 'TokenExpiredError',
message: 'jwt expired',
expiredAt: 1408621000
}
*/
}
});
In short words: Check the error of that method. If it is the TokenExpiredError then, guess what... the token is expired.
简而言之:检查该方法的错误。如果是 TokenExpiredError 那么,猜猜是什么...令牌已过期。
回答by lakshmankashyap
var isExpiredToken = false;
var dateNow = new Date();
if(decodedToken.exp < dateNow.getTime()/1000)
{
isExpiredToken = true;
}
回答by Pablo Almeidas
var isExpiredToken = false;
var dateNow = new Date();
if(decodedToken.exp < dateNow.getTime())
{
isExpiredToken = true;
}
回答by mchavezi
var isExpiredToken = false;
var seconds = 1000;
var d = new Date();
var t= d.getTime();
if (decoded.exp < Math.round(t / seconds)) {
// code...
isExpiredToken = true;
}
回答by cronosDevs
You need set the host current time to compare the expiration date in the verify function example:
您需要设置主机当前时间来比较验证函数示例中的到期日期:
jwt.verify(token, JWT.SECRET_KEY, {clockTimestamp: new Date().getTime()}, callback)
jwt.verify(token, JWT.SECRET_KEY, {clockTimestamp: new Date().getTime()}, callback)
the clockTimestamp property is required to set the host current time.
需要 clockTimestamp 属性来设置主机当前时间。
回答by Vladislav Hirsa
The best way set the code in your parent component of page or wrapper. Your need delete your old (expared) token.
在页面或包装器的父组件中设置代码的最佳方法。您需要删除旧的(扩展的)令牌。
let token = localStorage.getItem( 'token' );
jwt.verify( token, 'yourkey', function(err, decoded) {
if ( err ) {
localStorage.removeItem( 'token' );
}
} );

