jwt.verify not throwing error for expired tokens

雨燕双飞 提交于 2021-02-10 23:30:12

问题


I'm using JWT - jsonwebtokens in Nodejs.

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
}

In this case, my token is not expiring even after 2 minutes.

How can I achieve this?

Thanks


回答1:


In your code you added expiresIn as part of the payload. But there expiresIn has no meaning and you need to use the standard expclaim for expiration:

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. You can also calculate: (60 * minutes), (3600 * hours) or (86400 * days) for minutes, hours or days.

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.




回答2:


If you want to work with hours or minutes using expiresIn you need to declare it after your secret like this

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

Read more about it here



来源:https://stackoverflow.com/questions/63291152/jwt-verify-not-throwing-error-for-expired-tokens

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!