How to invalidate a JWT token with no expiry time

26,113

Solution 1

Looks like a familiar question to me, I have already answered the similar question Best practices to Invalidate a JWT Token .

So the steps for solving ur problem as follows,

when user login, create a login token in his user database with no expiry time.

Hence while invalidating a JWT, follow the below steps,

  • retrieve the user info and Check whether the token is in his User database. If so allow.
  • When user logs out, remove only this token from his user database.
  • When user changes his password, remove all tokens from his user database and ask him to login again.

So basically you need to store tokens in user's database and make use of it while invalidating. Simple :)

Solution 2

The exp claim of a JWT is optional. If a token does not have it it is considered that it does not expire

According to documentation of https://www.npmjs.com/package/jsonwebtoken the expiresIn field does not have a default value either, so just omit it.

var token = jwt.sign({email:'[email protected]',role:'User'}, "Secret", {});

Solution 3

you cannot invalidate your JWT token from what i know, i would always suggest always have a short expire time with maximum duration for a week,It may be be a pain to implement at first for your application to check if your token in valid from time to time and request a new one when invalid, there are provisions that allow you to refresh your token or check if the token is valid with most JWT libraries . Now if your are adamant that you want to keep your tokens without expire time then i would suggest keep a blacklist of sorts that your middle-ware will check. There was a similar question asked before here. Hope this helps

Share:
26,113
Admin
Author by

Admin

Updated on October 17, 2020

Comments

  • Admin
    Admin over 3 years

    Am creating a node.js backend app using JWT. For me the requirement is simple, that the authorization token shouldn't have any expiry time. But I am facing problem during invalidating JWT When user changes his password.

    When user changes his password, I will create a new JWT Token, and delete the old token, but still the user can use his old JWT token (from other logged in devices) and can access the application.

    So can anyone tell me how to avoid this scenario?

    • Sinandro
      Sinandro over 4 years
      Possible duplicate of How can I revoke a JWT token?
    • Billal Begueradj
      Billal Begueradj over 4 years
      the authorization token shouldn't have any expiry time: that is a wrong assumption from the security standpoint
  • Florian Walther
    Florian Walther almost 2 years
    I like this solution. But I noticed that your original answer in the other thread was much more complex. Why did you suggest storing the invalid tokens in the other answer, rather than just storing the active tokens in the user's DB entry (as you do here)?