The Role of Access and Refresh Tokens in Backend Authentication

The Role of Access and Refresh Tokens in Backend Authentication

Access and Refresh Tokens: Enhancing User Experience by Reducing Login Frequency

Access Token: Short lived (1d). It allows a user to stay logged in for a short duration. If the user gets logged out, they need to re-login.

Refresh Token: Long lived. It helps to trigger an end-point or to obtain a new Access Token.

But after some research, companies like Google propose an idea that users don't need to worry about re-login again and again.

So, how does it work?

i) In the backend, the Access Token is not stored. We give it to the user ,but we store another token called the Session Token (Refresh Token), which the backend developer keeps in database.

So let's suppose the user's Access Token has expired. So they will get a 401 error indicating that the Access Token has expired.

ii) Now the frontend develepor needs to write a feature that, upon receiving a 401 error, then the feature will hit an end-point to refresh user's Access Token, meaning the user will get a new Access Token.

Now how the user will get a new Access Token?

iii) Now, when the end-point (method) is triggered (called), we will receive a Refresh Token from the frontend as a request.

iv) Now, when the backend receives Session token (Refresh token) , it will match the incoming Refresh Token with the stored Refresh Token in the database. If both match, the backend will issue a new Access Token to the user.

- Happy Learing!