JSON Web Tokens - jwt
November 26, 2020

References

JWT Authentication Flow

JWT Authentication Flow

The flow of the authentication process is:

  1. User logs in using their credentials. On a successful login, the server issues an access token which is valid for a certain period of time (say 10 minutes) and a refresh token with a longer lifetime (say 24 hours for apps dealing with sensitive data. Simpler apps can have for days or even months). The client (frontend) stores refresh token in local storage (not database) and access token in cookies.
  2. On every request to a protected resource, the access token must be provided in the request as a header.
  3. When the access token expires after the stipulated time (10 minutes in our case), the client side app sends a request to generate a new access token, using the refresh token. This continues throughout the lifetime of the refresh token.
  4. Once the refresh token is expired, the user will be logged out and needs to log in again.

5 modules associated with the authentication process are:

  • register — Check database if existing with the given username. If there is no, create a new user and then log the user in. Generate an access token and a refresh token and send them as a response.
  • login — Verify the credentials of the user and then log the user in. Generate an access token and a refresh token and send them as a response.
  • generateRefreshToken — Check if the refresh token sent in the request body is valid by querying it in the database. After passing this check, it takes the payload stored in the refresh token and generates a new access token using it and sends it back to the client. This ensures that the user remains logged in.
  • logout — delete the refresh token sent in the request body from the database. The access token has to be deleted from the client side.
  • checkAuth — Check if the incoming request has the x-auth-token header and verify it against the private key. After passing these checks, the payload inside the access token is added to the request object. Appropriate errors are sent back to the client as and when required.