简体   繁体   中英

jwt.verify not throwing error for expired tokens

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?

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')

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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