Search code examples
javascriptreactjsmsal-react

Refresh access token automatically


For my site, I added a simple authorization page through microsoft (using the @azure/msal-react library). You can check out the demo version at the link https://codesandbox.io/s/wizardly-williams-j4bo42

After successful registration, the user is redirected to the site.

I'm satisfied with the job. But the problem is that the access token received during authorization lives only for one hour. Tell me how can I make it so that the access token is updated automatically.


Solution

  • In one of our most recent react apps we made use of an AxiosInterceptor component that is designed to handle HTTP response errors and automatically attempt a token refresh in case of 403 Unauthorized errors.

    When an axios request receives a response, the interceptor checks if there is an error. If there is no error, it simply returns the response.

    If the error code exists and the original request was not for the /auth/login endpoint, it checks if the response status is 403 Unauthorized and if the request hasn't already been retried.

    In case of 403, if the Authorization header of the original request equals the stored access token, it sets the Authorization header to the stored refresh token and attempts to refresh the tokens using the refreshTokenServices function.

    If the token refresh fails, or the Authorization header of the original request does not equal the stored access token, it redirects the user to the login page with an error message.

    The code would look something like this:

    // Response interceptor for API calls
    axiosApiInstance.interceptors.response.use((response) => {
      return response
    }, async function (error) {
      const originalRequest = error.config;
      if (error.response.status === 403 && !originalRequest._retry) {
        originalRequest._retry = true;
        const access_token = await refreshAccessToken();            
        axios.defaults.headers.common['Authorization'] = 'Bearer ' + access_token;
        return axiosApiInstance(originalRequest);
      }
      return Promise.reject(error);
    });
    

    Here is a great article about this:

    https://thedutchlab.com/blog/using-axios-interceptors-for-refreshing-your-api-token