1

I'm working on a React native application and I need to set Authentication header on my sensitive requests. But my accessToken (JWT) expires after 10 seconds. So before any request I have to check that if the token is expired renew it using a refreshToken and then call last request again.

I'm able to do all of these except last part (bold text).

And I'm using Axios for sending request to server. Any idea?

jps
  • 20,041
  • 15
  • 75
  • 79
Amin
  • 615
  • 7
  • 16

1 Answers1

2

So the idea is to use a response interceptor that works after the response is available, but before it is passed down in the code.

It looks for unauthenticated error, which corresponds to statusCode 401

Keep in mind that this is a pseudo-code and You have to modify some parts like auth.setToken().

const createAxiosResponseInterceptor = () => {
  const interceptor = axios.interceptors.response.use(
    (response) => response,
    (error) => {
      // Reject promise if not 401 error
      if (error.response.status !== 401) {
        return Promise.reject(error);
      }

      /*
       * When response code is 401, try to refresh the token.
       * Remove the interceptor so it doesn't loop in case
       * token refresh causes the 401 response
       *
       * Also eject the interceptor to prevent it from working again if the REFRESH request returns 401 too
       */
      axios.interceptors.response.eject(interceptor);

      return axios({
        url: API_REFRESH_URL,
        method: "POST",
        withCredentials: true,
      })
        .then((response) => {
          auth.setToken(response.data.access_token);
          error.response.config.headers["Authorization"] =
            "Bearer " + response.data.access_token;
          return axios(error.response.config);
        })
        .catch((error) => {
          auth.removeToken();
          return Promise.reject(error);
        })
        .finally(createAxiosResponseInterceptor);
    }
  );
};

createAxiosResponseInterceptor();

error.response.config contains all the data about the old request so we can repeat it. Keep in mind that after completing the Refresh request we again apply the interceptor in .finally(create...Interceptor)

For more details please see this question, and official Docs here

Davit
  • 793
  • 6
  • 17