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?
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?
Share Improve this question edited May 10, 2022 at 20:47 pppery 3,81425 gold badges37 silver badges50 bronze badges asked Aug 6, 2020 at 20:16 Prachi SharmaPrachi Sharma 3411 gold badge6 silver badges14 bronze badges 1- Are you using this library? – Matt Oestreich Commented Aug 6, 2020 at 20:32
2 Answers
Reset to default 4In 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