1
votes

I am implementing JWT in my project. I implemented jwt and gave it an expiration time of 1 minute. The jwt that is generated from the api side is during login and the token and expiration details are sent in the result and are stored in local storage. How can I refresh the expired token from API side and send it back again to the client so that it can be stored in local storage and sent for every call using interceptor?

this is how I created jwt and gave expiration time

// let us suppose this is my input
tokenObject = { User: { username: name, pwd: pwd } };
//creating a jwt here
jwt.sign({ tokenObject }, "secretkey", { expiresIn: "60s" }, (err, token) => {
  res.json({
    token
  });
});

After this, I'm verifying the token in the result and sending it in result to the client. After a minute how do I regenerate the token? Please help and let me know the way and tell me if I am doing something wrong . Thanks!!

2
I wouldn't accept expired tokens for refreshment.cassiomolin
What would be the correct way of implementing this ?user9065878
Expired tokens are invalid tokens per definition. You could use refresh tokens, that is long-lived tokens that allow you to refresh your access tokens or accept non-expired access tokens for refreshment.cassiomolin

2 Answers

2
votes

You need to add a function or middleware that will check that the JWT is valid or not. You can use the verify method of JWT library:

jwt.verify(token, 'secretKey', function (err, decoded) {
  if (err) {
    if (err.name === 'TokenExpiredError') {
       //create a new token and send the same way you created initially
    }
  }
});
0
votes

You can create an API that accepts a JWT token, validates it and then issues a new token for the same user.

Take a look at the verify method of jsonwebtoken. While verifying the token you can use ignoreExpiration: true option to verify the expired token as well. Then then generate the new one using sign method.
So while making the request from the frontend, if you get a token expired error, then you issue a new token using that API and save that token.

With that said, I do recommend you to take a look at the note about refreshing the JWT token from the docs:

First of all, we recommend to think carefully if auto-refreshing a JWT will not introduce any vulnerability in your system.

We are not comfortable including this as part of the library, however, you can take a look to this example to show how this could be accomplished. Apart from that example there are an issue and a pull request to get more knowledge about this topic.

Here is the link of the gist that has the code.