API rest with jwt for authentication. Why do we need a refresh token?

Viewed 149

So, i'm trying nest js for a side project. Reading a lot lately about jwt authentication flow. Conceptually, the flow would be something like:

  • Client logs in and receives and access token and a refresh token. Access Token will be short lived and will be stored in memory, not in localstorage, to reduce the risks of being stolen.
  • Refresh token will be used only when the access token is expired to get a new one. The new one will be stored in memory. The refresh token will be stored in an httpOnly cookie, so no javascript access will be allowed hence improving the security.

Everything is cristal clear, but, my question is... why do we need the access token and why don't we always use the refresh token? In the end, if we are trusting the refresh token to generate new access tokens... why don't we simplify the whole thing and use only the long lived, stored in an httpOnly cookie on every request?

I mean I get the whole process, I just don't get why is not "secure" to use the token stored in an httpOnly cookie every time.

Can anyone share some light here?

Thanks!

2 Answers

You use the access token to access the API. It contains the necessary claims to authenticate and authorize the request.

The refresh token is a separate token that you use to renew the access token and you can not use the refresh token to access any API, as it is typically just a random string without any specific meaning (no claims).

The refresh token is never sent to any API and having separate tokens gives a better separation of concerns. By using refresh tokens, we can have short-lived access tokens, so if the access token is stolen, it can only be used for a short time. The refresh token is stored in a more secure way and it is only used between the client and the identity provider, so there is less risk that it will be stolen or intercepted.

Some platforms (like ASP.NET core) stores the token by default in the session cookie) but to secure it it is encrypted using strong encryption. This means that the hacker or browser can't see the actual tokens inside the cookie.

More you travel, more you exposed. As you know the refresh token is meant to be used in case of short lived access token expiration. The idea for the use of two tokens is very simple. As access token (short lived token) will travel more frequently over the wire, increasing it chances of getting it caught by external parties. Therefore, short life expectency of access token will deny the access to the resouces for longer run in case of compromisation.

If the refresh token is secured, why don't we use just the refresh on every request?

Nothing can make the refresh token secure. It's totally client responsibility to store it in secure location/storage for later use.

Related