Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jwt check if token expired

I've configured the token like this:

jwt.sign(   {     user: pick(user, ['_id', 'username'])   },   secret,   {     expiresIn: '2m'   } ); 

But when I want to check if the token was expired, this code doesn't work:

function isAuthenticated() {   const token = localStorage.getItem('token');   const refreshToken = localStorage.getItem('refreshToken');   try {     decode(token);     const { exp } = decode(refreshToken);     if (exp < (new Date().getTime() + 1) / 1000) {       return false;     }   } catch (err) {     return false;   }   return true; } 

The problem is this part:

if (exp < (new Date().getTime() + 1) / 1000) {   return false; } 

new Date().getTime() + 1) / 1000 = 1531335468.113

exp = 1531334595

Because I don't know what format of time JWT uses...

How can I resolve this?

like image 792
Andrés Montoya Avatar asked Jul 11 '18 18:07

Andrés Montoya


People also ask

Does JWT verify check expiration?

verify with token and secret to verify the JWT token string against the secret string. It'll also check if token has expired.

How do you check if a JWT token is expired or not in spring boot?

Test Refresh Token with Spring Boot RestTemplate We will be modifying the code to test the refresh token scenario. Modify the TestController class. If we get the Expired JWT Exception, we will be creating a new refresh JWT and using it to get the data. Run the application to test refreshtoken url.

How do you handle expired JWT tokens?

In short, you need to use REFRESH_TOKEN when ACCESS_TOKEN expires to get a new ACCESS_TOKEN. JWT has two kind of tokens: ACCESS_TOKEN and REFRESH_TOKEN.

What happens if JWT token expires?

The JWT access token is only valid for a finite period of time. Using an expired JWT will cause operations to fail.


1 Answers

This is the answer:

if (Date.now() >= exp * 1000) {   return false; } 
like image 77
Andrés Montoya Avatar answered Sep 23 '22 13:09

Andrés Montoya