9

Good day,

I'm using jwt in my authentication. I already decoded my token but the problem is, I want to check if the token exp is already expired or not.

var decodedToken = localStorage.getItem('user_token');

console.log(decodedToken.exp) // writes 1540360205

Thank you in advance.

mark333...333...333
  • 1,270
  • 1
  • 11
  • 26
jsonGPPD
  • 987
  • 4
  • 16
  • 31

4 Answers4

24

It appears that the exp claim of your JWT tokens is bearing a UNIX timestamp, in seconds. To check if a given JWT is expired then you can just compare against the current date as a UNIX timestamp:

var decodedToken = localStorage.getItem('user_token');
if (decodedToken.exp < new Date()/1000) {
    console.log("EXPIRED");
}
Spectric
  • 30,714
  • 6
  • 20
  • 43
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • @erhan355 A JWT is both issued and checked/received by the same server, so timezones should not be any problem here. And, by design a JWT cannot be altered by a user without the server knowing that it has been hacked. – Tim Biegeleisen Feb 23 '20 at 12:44
  • If you have further needs not addressed by this question and accepted answer, you should open a new question, rather than stating your requirements in comments here. – Tim Biegeleisen Feb 23 '20 at 12:56
  • @erhan355 I see your doubt now. Keep in mind that this question didn't actually say that refresh tokens were being used (they don't have to be). To address your doubt, there should be a contract between the server and clients that a certain timezone, e.g. GMT, is being used for the expiration timestamp in `exp`. Then, clients may adjust as needed to figure out when they should should use the refresh token to request a new access and refresh token. – Tim Biegeleisen Feb 23 '20 at 13:24
  • 1
    Yes you got me.Thank you for clarafication. – erhan355 Feb 23 '20 at 14:43
2

This should get you the local time then you can compare it with current date and time and check if the token has expired

var tokenDate = new Date(parseInt(localstorage.getItem('user_token')) * 1000)
mark333...333...333
  • 1,270
  • 1
  • 11
  • 26
Nikhil Prasad
  • 65
  • 1
  • 10
  • There is no need for *parseInt*, the multiplication operator will coerce the result to number. – RobG Oct 23 '18 at 08:48
1

I assume that the value of decodedToken.exp is a UNIX timestamp of the token expiration date and thus you could just do the following:

...
var date = new Date();
// date.getTime() is in milliseconds and thus we've got to divide by 1000
if(decodedToken.exp<date.getTime()/1000){
    console.log('The token has expired');
}else{
    console.log('The token is still valid');
}
Sanosay
  • 536
  • 5
  • 18
1

you can compare using Date.now() as follows

     decodedToken.exp * 1000 < Date.now()

PS: I've multiplied exp * 1000 to get it in ms.

Mohammed Essehemy
  • 2,006
  • 1
  • 16
  • 20