jwt and refresh tokens

A token created with 3 inputs.

a resulting jwt is a base64 encoded string separated in 3 sections by a . char
1st section is header that specifies algorithm used.
2nd section is payload: data
3rd section is used to verify signature.

data inside a jwt is public, anyone can decode and see the data in it.
jwt is signed with a secret to verify the sender and that the data inside the token wasn't modified.
Although it is possible to encrypt the contents of a jwt, if the use case merits it.

You can't invalidate jwt earlier than the issued expiration date. Implementing a Log out of all devices becomes an issue bc of this. Also Hackers can take advantage of longlived jwt if they get to steal them.

This is why you usually jwt to be shortlived, but this would create the inconvenience of logging the user out all the time.

The solution is when user logs in you actually serve them 2 tokens: accessToken and refreshToken.

imagina access token expires in 15 minutes and refresh token in 30 days.
when the access token is valid user can make API calls, when it expires it checks the refreshToken and serves a new accessToken if it is.

  1. checks if refresh is valid
  2. check DB to see if user should still be allowed to be logged in (?idk how to do this)
  3. create new access token (and give them new 30 day refreshToken if you want)

This way you only do a DB query once every 15 mins instead of every request (in the case of using Sessions).

to check if user should still be logged in (log out of all devices feature example).

  1. You store a refreshTokenVersion on user table
  2. when you create a refreshToken, put that version inside of it
  3. when you validate refreshToken check whether version matches the one in the DB
  4. if it doesn't, token is considered invalid.
    when user clicks the log out of all devices button, you update the refreshTokenVersion of the user by +1.

where to store

advantages and disadvantaes

advantages

disadvantages

reference

https://www.youtube.com/watch?v=CcrgG5MjGOk