jwt.verify不会为过期的令牌抛出错误 [英] jwt.verify not throwing error for expired tokens
问题描述
我正在使用JWT-Node.js中的jsonwebtokens.
I'm using JWT - jsonwebtokens in Nodejs.
我正在创建一个令牌,如果令牌过期,我想抛出一个错误.我的令牌已成功创建,并且我正在Expressjs中的Apis中间件中检查令牌到期.然后从Angular的标头中发送令牌,并在中间件中检查到期时间.
I'm creating a token and want to throw an error if the token expires. My token is created successfully and I'm checking the token expiry in middleware of Apis in Expressjs. Then token is sent from Angular in headers and the expiration is checked in middleware.
这是我创建令牌的方式:
This is how I'm creating the token:
var token = jwt.sign({
id: id,
expiresIn: '2m'
},
'mysecretkey'
);
这是我的中间件的外观:
This is how my middlware looks like:
var token = req.headers['authorization']
var idToken = token.split(' ')[1]
if(token) {
jwt.verify(idToken, 'myscretkey', (err, decoded) => {
if(err) {
return res.status(400).send('Session expired')
}
next()
})
}
这是我在解码后的
中收到的内容:
This is what I'm receiving in decoded
:
dec: {
id: 'an id',
expiresIn: '2m',
iat: 1596744770
}
在这种情况下,即使过了2分钟,我的令牌也没有过期.
In this case, my token is not expiring even after 2 minutes.
我该如何实现?
谢谢
推荐答案
在代码中,您添加了 expiresIn
作为有效负载的一部分.但是, expiresIn
没有意义,您需要使用标准的
In your code you added expiresIn
as part of the payload. But there expiresIn
has no meaning and you need to use the standard exp
claim for expiration:
jwt.sign({
id: 'an id',
exp: Math.floor(Date.now() / 1000) + (60 * 2),
iat: Math.floor(Date.now())
}, 'secret')
在此示例中为2分钟.您还可以计算:(60 *分钟),(3600 *小时)或(86400 *天)持续数分钟,数小时或数天.
in this example it's 2 minutes. You can also calculate: (60 * minutes), (3600 * hours) or (86400 * days) for minutes, hours or days.
expiresIn
用作sign方法的一个选项,如Shivam Soods答案所示.我认为这就是您感到困惑的原因.
expiresIn
can be used as an option to the sign method as shown in Shivam Soods answer. I think that's the reason for your confusion.
这篇关于jwt.verify不会为过期的令牌抛出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!