ASP.NET Core 2.2 REST API #12.5 — What is a Refresh Token and why your REST API needs it

Theodoros Ntakouris
2 min readJul 23, 2019

--

Up Next: Refreshing JWTs with Refresh Tokens

Before we proceed to refresh our JWT tokens as soon as they expire, we need to explain a very simple concept: Refresh Tokens.

Up until now, authorisation procedure is pretty straightforward:

  • POST /login with an email and a password
  • Retrieve the JWT
  • Store the JWT locally
  • Pass the JWT inside the header on every request that is sent to the API

However, the JWT expires, typically in a few hours. We don’t want to repeat the above procedure every time the token expires. It would be a very bad user experience to be presented with a login prompt every few hours.

Solution: Refresh Tokens

We are going to issue a refresh token along with the JWT. The JWT can have a very short lifespan, for example, 1 minute, but the refresh token is going to have a much bigger expiry date, for example, 6–12 months.

Now, even if someone intercepts our JWT while talking to the main application API, they only have access to that for a few minutes, without having access to the refresh token. Extra security points.

Re-issuing the token is non trivial:

  • Send the expired JWT and the refresh token
  • Check the validity of the JWT and refresh token
  • Issue a new pair for the user

The refresh token can be invalidated as well, for example if we have a data breach or some other important security incident.

From a client’s point of view, stuff are pretty simple and transparent from the user:

  • Upon login, save the token pair locally
  • Use middleware to send the JWT on every request with the Bearer auth scheme
  • Upon some HTTP 401 — or expired JWT, try to refresh the token before proceeding with the request
  • If that fails, present the login prompt because the refresh token is invalidated

Code is available on Github and the instructional videos are located on YouTube.

Keep Coding

--

--

No responses yet