The flow of the authentication process is:
- 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.
- On every request to a protected resource, the access token must be provided in the request as a header.
- 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.
- 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-tokenheader 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.