简体   繁体   English

jwt.verify 不会为过期令牌抛出错误

[英]jwt.verify not throwing error for expired tokens

I'm using JWT - jsonwebtokens in Nodejs.我在 Nodejs 中使用 JWT - jsonwebtokens。

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.我的令牌已成功创建,我正在 Expressjs 中的 APIs 中间件中检查令牌是否过期。 Then token is sent from Angular in headers and the expiration is checked in middleware.然后令牌从 Angular 在标头中发送,并在中间件中检查过期。

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 :这是我在decoded时收到的:

dec:  {
  id: 'an id',
  expiresIn: '2m',
  iat: 1596744770
}

In this case, my token is not expiring even after 2 minutes.在这种情况下,我的令牌即使在 2 分钟后也不会过期。

How can I achieve this?我怎样才能做到这一点?

In your code you added expiresIn as part of the payload.在您的代码中,您添加了expiresIn作为有效负载的一部分。 But there expiresIn has no meaning and you need to use the standard exp claim for expiration:但是expiresIn没有意义,你需要使用标准的exp声明来过期:

jwt.sign({
  id: 'an id',
  exp: Math.floor(Date.now() / 1000) + (60 * 2),
  iat: Math.floor(Date.now())
}, 'secret')

in this example it's 2 minutes.在本例中为 2 分钟。 You can also calculate: (60 * minutes), (3600 * hours) or (86400 * days) for minutes, hours or days.您还可以计算:(60 * 分钟)、(3600 * 小时) 或 (86400 * 天) 的分钟、小时或天数。

expiresIn can be used as an option to the sign method as shown in Shivam Soods answer. expiresIn可以用作 sign 方法的一个选项,如 Shivam Soods 回答中所示。 I think that's the reason for your confusion.我想这就是你困惑的原因。

If you want to work with hours or minutes using expiresIn you need to declare it after your secret like this如果您想使用expiresIn处理hoursminutes ,您需要像这样在您的secret之后声明它

let token = jwt.sign(id,'mysecretkey',{ expiresIn: '1h'});

Read more about it here 在此处阅读有关它的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM