CommunityOfCoders / COCWebsite

The official website of Community Of Coders, VJTI.

Home Page:https://www.communityofcoders.in

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Increase the JWT validation time, or auto refresh the token

ShubhankarKG opened this issue · comments

If our user stays logged in for a long period of time, they won't be able to access the API because of JWT Expired. Either we increase the JWT validation time, or we implement some sort of auto refresh token in our client side.

Rather than increasing the validation time, we can set up a silent refresh of JWT token.

Steps

  • Add 2 new fields to the user database schema, last_active, which stores DateTime of last request and refresh_token which is a boolean which stores whether or not the token should be refreshed for the given user.

  • Create a new endpoint /refresh_token. A request is sent on this endpoint when the token is expired. We check 2 conditions here before refreshing

    1. current_date - last_active < some x days. If this is false set refresh_token = false. This helps when the user hasn't been active in for greater than x days in which case no new token will be generated and the user will have to login
    2. If refresh_token === true, generate and return new JWT token to the client, else return 401 status code and redirect the client to login

Examples

User logs in/registers

  • Update last_active
  • Set refresh_token = true
  • Return new JWT token

User sends a request

Case 1: JWT is valid

  • Normal operation with status code 200

Case 2: JWT has expired

  • Catch error code 401 and send a request to /refresh_token
  • Returns new token and status code 200 if all conditions are satisfied
  • Else returns error code 401 and client redirects to login

User logs out

  • Set refresh_token = false
  • Delete token from client storage

User has been inactive for a long time and then sends a request

  • First 401 will be caught if the client uses the old token stored at the client side.
  • Request will be sent to /refresh_token which will fail and return 401 and client will be redirected to login

We do have a /verify-token route here. Perhaps it's now time to use it out.

We'll have to refactor this to add the new token generation code. Currently /verify-token just checks whether token is active or not.