Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to do JWT expiration with Node.js and jsonwebtoken?

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.

like image 401
albertot_dev Avatar asked Mar 29 '17 15:03

albertot_dev


People also ask

How do you set the expiry on a JWT?

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 });

Where is JWT expiration stored?

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.

How can I get expiry from JWT token?

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.

How do you check JWT token is expired or not in node JS?

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.


1 Answers

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.

like image 57
Joe Clay Avatar answered Oct 13 '22 21:10

Joe Clay