Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the ways to implement logout from all devices feature with JWT token mechanism?

I want to implement JWT in my next project. I just want to know if there is any best way to implement logout from all devices in JWT. As JWT is stateless mechanism, do we have to involve redis/db?

like image 589
Kaphy Avatar asked Apr 29 '16 05:04

Kaphy


2 Answers

If you just want to remove the token, it will be simple as removing it from the front end application, In you case clear the cookies that stores the token

On the other hand if you mean to invalidate the token, there is couple of ways to do it, below are some ways

(1) If all the token ever generated is stored in backend, It will be just simple as clearing that storage, if tokens have been mapped to users you can just clear tokens for a particular user.

(2) You can add a date field like "invalidate_before" along with user which should be updated at a event of changing password, logout from all devices etc. Simply update the invalidate_before to currentTime() on such events. Every time a new token is created, add the created time in token payload, to validate the token on incoming request just check if the created time in payload is greater than invalidate_before time for that user in db

(3) When you create a new user, create a secret for just that user, then you can sign every user token with that specific secret, and just like in (2) events like changing password, logout from all devices etc, Should create a new secret. This way also you can invalidate by checking the token signature.

overhead with (2) and (3) is that, validation will be a 2 step process and it involves db reading

EDIT: For (3) you may use a salt instead (final secret will be common secret + salt for particular user), So that you hava a way to invalidate either a single user's token by changing salt or the all user's token by changing common secret

like image 69
Akshay Som Avatar answered Sep 26 '22 09:09

Akshay Som


Can we Save a random JWT secret in the DB when new user is created? If we want to sign out all devices, just generate new Secret, so all OLD Tokens are invalid now. And for normal Logout, just delete the Token in the Front End

like image 44
Hồ Thiện Lạc Avatar answered Sep 24 '22 09:09

Hồ Thiện Lạc