0

Hi I am new to the front end flow of JWT auth and was wondering how to resend a request when a new token is issued.

From my understanding Auth tokens should be short-lived, while Refresh tokens have a longer life span. This causes an issue where requests frequently fail due to expired auth token and a request has to be sent again with a new auth token.

What is the best practice in maintaining this pattern? As a POC I wrote quick snippet to showcase an idea I had, but feel there might be a better way.

const API_FETCH_ATTEMPTS = 2; 
const refreshAPI = 'backend/refresh';

function customFetch(url, options, retryAttempts = API_FETCH_ATTEMPTS){

  if (!retryAttempts){
    return null 
  }
  const authToken = localStorage.getItem('auth-token');
  return fetch(url, {...options,'AuthToken': authToken})
    .then()// successful call
    .catch(err => {
      if (err.status === '401'){
        fetch(refreshAPI)
          .then(newToken => {
            localStorage.setItem('authToken', newToken)
            customFetch(url, options, retryAttempts - 1);
          });
      }
    });
}

Any ideas / assistance is much appreciated. Thanks!

Eric
  • 31
  • 5

1 Answers1

2

You are on the right tracks:

  • Expect 401s
  • Refresh the access token
  • Retry the API call once only, with the new token
  • Redirect the user to sign in again if token refresh fails

My preference is to use 2 classes:

  • A service agent to call the API
  • An authenticator class to do the OAuth work

Here is some sample code of mine, though you can implement this design pattern in any client side language:

Gary Archer
  • 22,534
  • 2
  • 12
  • 24