I am creating a web application based on MEAN and I have the following question:
Where is it better to put a token (JWT) expiration? Right now what I am doing is to create a token without expiration and in the client, I created a cookie with that token and 10 minutes of expiration.
In that cookie, I add 10 minutes in every request I make. If the user is inactive for 10 minutes that cookie expires and the request is made without a token.
var token = jwt. sign({email_id:'[email protected]'}, "Stack", { expiresIn: "10h" // it will be expired after 10 hours //expiresIn: "20d" // it will be expired after 20 days //expiresIn: 120 // it will be expired after 120ms //expiresIn: "120s" // it will be expired after 120s });
The expiration is saved inside the CLAIM. As written in the RFC. The "exp" (expiration time) claim identifies the expiration time on or after which the JWT MUST NOT be accepted for processing.
You can use a lib(like jwt_decode) to decode your JWT token, where it's most likely contains an expiration timestamp that you can check(compare it with the current timestamp for this moment) and if it exceeded(expired) just delete it from local storage and redirect user to login page.
verify method to a function that returns a promise and assign it to jwtVerifyAsync . Then we call jwtVerifyAsync with the token and the token secret to check if the token is valid. If it's expired, then it's considered invalid and an error will be thrown.
In Chrome:
F12 ➡️ Application tab ➡️ Cookies ➡️ Copy and paste token into a REST client like Postman
Whoops, I just got an everlasting token for your API!
In other words, as you suspected, this isn't a good way of doing things. The expiration should be in the token's payload - that way, you can verify nobody has altered it, as it'll be signed with your server secret value.
The Node JWT library actually has this functionality built-in:
jwt.sign({
// 1 hour expiration
exp: Math.floor(Date.now() / 1000) + (60 * 60),
data: 'foobar'
}, 'secret');
This isn't to say that you can't/shouldn't also use cookie expiration with your tokens, but relying on it alone isn't secure.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With