Flyrell / axios-auth-refresh

Library that helps you implement automatic refresh of authorization via axios interceptors. You can easily intercept the original request when it fails, refresh the authorization and continue with the original request, without user even noticing.
MIT License
1.06k stars 91 forks source link

Request is not being re-triggered after re-auth #194

Closed rota-rossi closed 2 years ago

rota-rossi commented 2 years ago

Symptom: after receiving a 401 error, the refresh endpoint is called, and the following requests properly use the new access token - but the original request is never re-triggered, and the auth action returns TypeError: undefined is not a function.

Code:

// use axios-case-converter to convert snake case (e.g. created_time) to camel case (e.g. createdTime)
const axiosInstance = applyCaseConverters(
  axios.create({
    baseURL: Config.BASE_URL + 'api/',
  }),
  {
    ignoreHeaders: true,
  }
);

// few other interceptors omitted - but tried to disable all of them and the error still persists

// add JWT access token to all request header if present
axiosInstance.interceptors.request.use(request => {
  request.headers!.Authorization = `Bearer ${getToken('access')}`;
  return request;
});

const refreshAuthLogic = (failedRequest: any) =>
  axiosInstance
    .post(`/auth/token/refresh/`, { refresh: getToken('refresh') })
    .then(result => {
      setToken('access', result.data.access);
      failedRequest.response.config.headers.Authorization =
        'Bearer ' + result.data.access;
      return Promise.resolve();
    });

createAuthRefreshInterceptor(axiosInstance, refreshAuthLogic, {
  pauseInstanceWhileRefreshing: true,
});

Can someone point me what I might be doing wrong?

DovahBrownies commented 2 years ago

Have you tried removing pauseInstanceWhileRefreshing?

Flyrell commented 2 years ago

See request interceptor example in the docs. Basically for other requests you should have an interceptor that binds that token when they're triggered (as the token might have changed if the first request is caught in the refreshAuthLogic callback adn you re-authorize the user).