node.js jwt 检查令牌是否过期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51292406/
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
jwt check if token expired
提问by Andrés Montoya
I've configured the token like this:
我已经像这样配置了令牌:
jwt.sign(
{
user: pick(user, ['_id', 'username'])
},
secret,
{
expiresIn: '2m'
}
);
But when I want to check if the token was expired, this code doesn't work
但是当我想检查令牌是否过期时,此代码不起作用
function isAuthenticated() {
const token = localStorage.getItem('token');
const refreshToken = localStorage.getItem('refreshToken');
try {
decode(token);
const { exp } = decode(refreshToken);
if (exp < (new Date().getTime() + 1) / 1000) {
return false;
}
} catch (err) {
return false;
}
return true;
}
The problem is this part:
问题是这部分:
if (exp < (new Date().getTime() + 1) / 1000) {
return false;
}
new Date().getTime() + 1) / 1000 = 1531335468.113
新日期().getTime() + 1) / 1000 = 1531335468.113
exp = 1531334595
exp = 1531334595
Because I don't know what format of time uses JWT...
因为不知道JWT用的是什么格式的时间...
How can I resolve this?
我该如何解决这个问题?
Thank you!
谢谢!
回答by Andrés Montoya
This is the answer if someone want to know
如果有人想知道,这就是答案
if (Date.now() >= exp * 1000) {
return false;
}
回答by Gabriel Bleu
You should use jwt.verifyit will check if the token is expired. jwt.decodeshould not be used if the source is not trusted as it doesn't check if the token is valid.
您应该使用jwt.verify它会检查令牌是否已过期。 如果来源不受信任,则不应使用jwt.decode,因为它不检查令牌是否有效。
回答by Rashomon
verifyitself returns an error if expired. Safer as @Gabriel said.
verify如果过期,本身会返回错误。正如@Gabriel 所说,更安全。
const jwt = require('jsonwebtoken')
router.use((req, res, next) => {
const token = yourJwtService.getToken(req) // Get your token from the request
jwt.verify(token, req.app.get('your-secret'), function(err, decoded) {
if (err) throw new Error(err) // Manage different errors here (Expired, untrusted...)
req.auth = decoded // If no error, token info is returned in 'decoded'
next()
});
})
回答by lony
Sadly @Andrés Montoya answer has a flaw which is related to how he compares the obj. I found a solution herewhich should solve this:
可悲的是@Andrés Montoya 的回答有一个缺陷,这与他比较 obj 的方式有关。我在这里找到了一个应该解决这个问题的解决方案:
const now = Date.now().valueOf() / 1000
if (typeof decoded.exp !== 'undefined' && decoded.exp < now) {
throw new Error(`token expired: ${JSON.stringify(decoded)}`)
}
if (typeof decoded.nbf !== 'undefined' && decoded.nbf > now) {
throw new Error(`token expired: ${JSON.stringify(decoded)}`)
}
Thanks to thejohnfreeman!
感谢约翰弗里曼!
回答by gauravsbagul
This is for react-native, but login will work for all types.
这是针对本机的,但登录适用于所有类型。
isTokenExpired = async () => {
try {
const LoginTokenValue = await AsyncStorage.getItem('LoginTokenValue');
if (JSON.parse(LoginTokenValue).RememberMe) {
const { exp } = JwtDecode(LoginTokenValue);
if (exp < (new Date().getTime() + 1) / 1000) {
this.handleSetTimeout();
return false;
} else {
//Navigate inside the application
return true;
}
} else {
//Navigate to the login page
}
} catch (err) {
console.log('Spalsh -> isTokenExpired -> err', err);
//Navigate to the login page
return false;
}
}
回答by Pramuditha
Catch the error of token and handle it from this.
捕获令牌的错误并从中处理它。
public boolean validateToken(String authToken) {
try {
Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(authToken);
return true;
} catch (SignatureException ex) {
//Invalid token signature
} catch (MalformedJwtException ex) {
//Invalid token
} catch (ExpiredJwtException ex) {
//Expired token
} catch (UnsupportedJwtException ex) {
//Unsupported token
} catch (IllegalArgumentException ex) {
//Token claims string is empty
}
return false;
}
回答by Zaur
// Pass in function expiration date to check token
function checkToken(exp) {
if (Date.now() <= exp * 1000) {
console.log(true, 'token is not expired')
} else {
console.log(false, 'token is expired')
}
}

