0

This question talks about the theory and work flow behind using refresh tokens to prolong the life of the access token.

As the linked answer suggest, I should do expiry check (1) when the app is opened, and (2) periodically every x hour, and refresh the access token if it is near expiring.

My question is, how exactly do I implement this in React, or any front end code?

Suppose my single page app has 3 pages, each with 5 components.

When the user opens the app, it could be any of the 3 URLs, which component (if any) should be responsible for this check? Should this block any of the other components from fetching data until the verification is done?

Similarly, which component (if any) should do the period checking?

I'm thinking that as long as the above 2 is correctly executed, it will not be possible to end up in a situation where a user makes a request with an expired access token. At least, I can't think of an edge case that an expired access token will be sent. Is this correct?

Peppershaker
  • 111
  • 1
  • 8

1 Answers1

1

Ideally, you would have a handler in your API calls that would check to see if the JWT is expiring soon and preemptively perform an additional call to the server to request a replacement token. If a user is actively interacting with your application, the refresh should occur when needed and not more often, reducing the number of calls to your application.

In one of my projects, we have an APIClient class that contains methods for all of the calls we need to do, such as getOwnUser and getTicketById, which each call a method that actually performs the request, fetchJSON.

The fetchJSON method checks the validity of the JWT using a date stored in a cookie before performing the request. If it's near expiration or expired, the method will perform another call to request a new token using a refreshToken issued at the time the original (or subsequent replacement) token is issued. If the old token isn't yet expired, both of these calls could be performed simultaneously so there's no lag for the user.

A downside to this is that the existing potentially unexpired JWT is still valid and can still be used(!) if it were obtained. To rectify that, you could simply just wait until the JWT expires before renewing it though this may cause a momentary lag for the user while the additional call occurs. Although, this is the outcome you're trying to avoid.

So long as you avoid storing the JWT and refresh token (if you choose to use it) in localstorage, you should be fine. You should also ensure that the validity length of your JWT is reasonably short (We use 15 minutes) as it's impossible to revoke them without slowing down your server-side validation and making their use kind of pointless.