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'

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

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?


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 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:

  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.

Method 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

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x