48

We've recently discussed an axios' interceptor for OAuth authentication token refresh in this question.

What the interceptor should do is intercept any response with the 401 status code and try to refresh the token. With that in mind, the next thing to do is to return a Promise from the interceptor, so that any request which would have normally fail, would run as nothing happens after a token refresh.

The main problem is, that an interceptor checks only the 401 status code, which is not enough, as the refreshToken will also return the 401 status code when it fails - and we have a loop.

There are two possible scenarios I have in mind:

  1. check the called URL, so if that's /auth/refresh it shouldn't try to refresh the token;
  2. omit an interceptor when the refreshToken logic is called

The first option looks a bit "not dynamic" to me. The second option looks promising, but I'm not sure if it's even possible.

The main question is then, how can we differentiate/identify calls in an interceptor and run different logic for them without "hardcoding" it specifically, or is there any way to omit the interceptor for a specified call? Thank you in advance.

The code for an interceptor might help to understand the question:

Axios.interceptors.response.use(response => response, error => {
    const status = error.response ? error.response.status : null

    if (status === 401) {
        // will loop if refreshToken returns 401
        return refreshToken(store).then(_ => {
            error.config.headers['Authorization'] = 'Bearer ' + store.state.auth.token;
            error.config.baseURL = undefined;
            return Axios.request(error.config);
        })
        // Would be nice to catch an error here, which would work if the interceptor is omitted
        .catch(err => err);
    }

    return Promise.reject(error);
});

and token refreshing part:

function refreshToken(store) {
    if (store.state.auth.isRefreshing) {
        return store.state.auth.refreshingCall;
    }

    store.commit('auth/setRefreshingState', true);
    const refreshingCall = Axios.get('get token').then(({ data: { token } }) => {
        store.commit('auth/setToken', token)
        store.commit('auth/setRefreshingState', false);
        store.commit('auth/setRefreshingCall', undefined);
        return Promise.resolve(true);
    });

    store.commit('auth/setRefreshingCall', refreshingCall);
    return refreshingCall;
}

7 Answers 7

120
+100

I may have found a way much simpler to handle this : use axios.interceptors.response.eject() to disable the interceptor when I call the /api/refresh_token endpoint, and re-enable it after.

The code :

/**
 * Wrap the interceptor in a function, so that i can be re-instantiated
 */
function createAxiosResponseInterceptor() {
    const interceptor = axios.interceptors.response.use(
        (response) => response,
        (error) => {
            // Reject promise if usual error
            if (error.response.status !== 401) {
                return Promise.reject(error);
            }

            /*
             * When response code is 401, try to refresh the token.
             * Eject the interceptor so it doesn't loop in case
             * token refresh causes the 401 response.
             *
             * Must be re-attached later on or the token refresh will only happen once
             */
            axios.interceptors.response.eject(interceptor);

            return axios
                .post("/api/refresh_token", {
                    refresh_token: this._getToken("refresh_token"),
                })
                .then((response) => {

                    saveToken();
                    error.response.config.headers["Authorization"] =
                        "Bearer " + response.data.access_token;
                    // Retry the initial call, but with the updated token in the headers. 
                    // Resolves the promise if successful
                    return axios(error.response.config);
                })
                .catch((error2) => {
                    // Retry failed, clean up and reject the promise
                    destroyToken();
                    this.router.push("/login");
                    return Promise.reject(error2);
                })
                .finally(createAxiosResponseInterceptor); // Re-attach the interceptor by running the method
        }
    );
}
createAxiosResponseInterceptor(); // Execute the method once during start

Above code will:

  • intercept calls which are returned with a https status code 401
  • eject the interceptor, preventing infinite loop
  • Fetch a new token
  • duplicate and modify the initial request, by replacing the old with the new token
  • retry the initial request with the new token in the header
  • re-attach the interceptor after the retry request, regardless of the outcome.
11
  • 7
    Sorry, But I don't know how can I use that solution, Can you please provide a hint in which show how to inject that function into axios. Jun 17, 2019 at 6:39
  • 8
    Surely that would mean that any pending requests that return before the refresh request won't get caught by the interceptor, and thus won't be retried when the new token is received
    – Tam Coton
    Aug 20, 2019 at 10:48
  • 2
    How can I use this function into my axios config? Nov 6, 2019 at 14:09
  • 1
    for those who don't know how to use the solution, it is as easy as call the function createAxiosResponseInterceptor() no need to change in axios config. Mar 23, 2020 at 4:22
  • 5
    To use the interceptor: axios.interceptors.response.use(createAxiosResponseInterceptor); Read more here : github.com/axios/axios#interceptors
    – Ash Singh
    Nov 9, 2020 at 14:47
10

Not sure if this suits your requirements or not, but another workaround could also be the separate Axios Instances (using axios.create method) for refreshToken and the rest of API calls. This way you can easily bypass your default interceptor for checking the 401 status in case of refreshToken.

So, now your normal interceptor would be the same.

Axios.interceptors.response.use(response => response, error => {
  const status = error.response ? error.response.status : null

  if (status === 401) {
    // will loop if refreshToken returns 401
    return refreshToken(store).then(_ => {
      error.config.headers['Authorization'] = 'Bearer ' + store.state.auth.token;
      error.config.baseURL = undefined;
      return Axios.request(error.config);
    })
    // Would be nice to catch an error here, which would work, if the interceptor is omitted
    .catch(err => err);
  }

  return Promise.reject(error);
});

And, your refreshToken would be like:

const refreshInstance = Axios.create();

function refreshToken(store) {
  if (store.state.auth.isRefreshing) {
    return store.state.auth.refreshingCall;
  }

  store.commit('auth/setRefreshingState', true);
  const refreshingCall = refreshInstance.get('get token').then(({ data: { token } }) => {
    store.commit('auth/setToken', token)
    store.commit('auth/setRefreshingState', false);
    store.commit('auth/setRefreshingCall', undefined);
    return Promise.resolve(true);
  });

  store.commit('auth/setRefreshingCall', refreshingCall);
  return refreshingCall;
}

here are some nice links [1] [2], you can refer for Axios Instances

0
7

This is my implementation that avoids the infinite loop if the refresh route returns 401.

To avoid the infinite loop, I am using a clean instance of axios without the interceptor to refresh the token.

I am using cookies but you can refer to the other answers if you are using localStorage.

src/api/index.js

import axios from 'axios'

const baseURL = process.env.NODE_ENV === 'production' ? '/api' : http://localhost:5000/api`

const axiosInstance = axios.create({
  baseURL,
  timeout: 30000
})

axiosInstance.interceptors.response.use(response => response, error => {
  const { response, config } = error

  if (response.status !== 401) {
    return Promise.reject(error)
  }

  // Use a 'clean' instance of axios without the interceptor to refresh the token. No more infinite refresh loop.
  return axios.get('/auth/refresh', {
    baseURL,
    timeout: 30000
  })
    .then(() => {
      // If you are using localStorage, update the token and Authorization header here
      return axiosInstance(config)
    })
    .catch(() => {
      return Promise.reject(error)
    })
})

export default axiosInstance

I am using Vue on the frontend.

1
  • 1
    Considering this was never upvoted, I was surprised to see this was the only solution that worked for me. Thanks!
    – hatef
    Apr 11, 2022 at 12:33
0

I'm using react for building frontend side of my applications and regularly using almost the same strategy to solve such kind of problems

#ReactJs #JasvaScript #Axios

import axios from 'axios';

const baseURL = process.env.REACT_APP_SERVICE_URL;

const service = axios.create({ baseURL });

function saveToken(access_token, refresh_token) {
  sessionStorage.setItem('access_token', access_token);
  sessionStorage.setItem('refresh_token', refresh_token);
}
function destroyToken() {
  sessionStorage.removeItem('access_token');
  sessionStorage.removeItem('refresh_token');
}
function refresh() {
  return new Promise((resolve, reject) => {
    service.post('/api/v1/refresh', {
      refresh_token: sessionStorage.getItem('refresh_token')
    }).then((response) => {
      saveToken(response.data.access_token, response.data.refresh_token);
      return resolve(response.data.access_token);
    }).catch((error) => {
      destroyToken();
      window.location.replace('/logout');
      return reject(error);
    });
  });
}

service.interceptors.response.use(
  (res) => res,
  (error) => {
    const status = error.response ? error.response.status : null;
    if (status === 401) {
      window.location.replace('/logout');
      sessionStorage.removeItem('access_token');
      sessionStorage.removeItem('refresh_token');
    }
    // status might be undefined
    if (!status) {
      refresh();
    }
    return Promise.reject(error);
  }
);

service.interceptors.request.use((config) => {
  const access_token = sessionStorage.getItem('access_token');
  config.headers.Authorization = `Bearer ${access_token}`;
  return config;
});

export { service };

In my case sometimes error.response was undefined, so that is why I first updated access token if there is and error then logout
0

My implementation option

~/main.js

Vue.use(axiosPlugin, {store})

~/plugins/axios.js

import axios from 'axios'
import JWT from '@/utils/jwt'
import {AuthService} from '@/services/auth.service'

const UNAUTHORIZED_URLS = [
    '/auth/login',
    '/auth/token/refresh',
    '/user/create'
]

export default {
    async requestInterceptor(config) {

        /* Token validation and adding Authorization header */
        if (!UNAUTHORIZED_URLS.includes(config.url)) {
            if (!JWT.validateToken(this.store.getters['auth/accessToken'])) {
                await this.store.dispatch('auth/refreshUserToken')
            }

            config.headers['Authorization'] = AuthService.getAuthorizationHeader()
        }
    
        return config
    },
    async responseErrorInterceptor(error) {
        if (![401, 419].includes(error.response.status)) {
            return Promise.reject(error)
        }

        /* If this is a repeated request */
        if (error.response.config._retry) {
            await this.store.dispatch('auth/logout')

            return Promise.reject(error)
        }

        /* Attempting to update the token and retry the request */
        try {
            this.store.dispatch('auth/refreshUserToken')

            error.response.config._retry = true

            error.response.config.headers['Authorization'] = AuthService.getAuthorizationHeader()

            return axios(error.response.config)
        } catch (error) {
            await this.store.dispatch('auth/logout')

            return Promise.reject(error)
        }
    },
    install(Vue, options) {
        axios.defaults.baseURL = process.env.VUE_APP_BASE_URL
        axios.interceptors.request.use(this.requestInterceptor.bind(options))
        axios.interceptors.response.use(undefined, this.responseErrorInterceptor.bind(options))
    }
}
0

In my case axios.interceptors.response.eject() disable the interceptor but doesn't re-enable it. So, I checked the refresh token (whether it is expired or not)

const interceptor = $axios.interceptors.response.use(
          response => response,
          error => {
              // Reject promise if usual error
              if (error.response.status !== 401) {
                  return Promise.reject(error);
              }
              
              // Logout if Refresh token expires.
              if(error.response.config.url == 'your_response_url_after_refresh_token_expire') {
                localStorage.clear();
                $nuxt.$router.push("/");
                return Promise.reject(error);
              }
              
              // If refresh token is working
              let refreshToken = {'refresh': localStorage.getItem('refresh')}
                return $axios.post('/api/refresh_token', refreshToken)
                  .then((response) => {
                    localStorage.setItem('access', response.data.access)
                    return $axios(error.response.config);
                  }).catch((err) => {
                    localStorage.clear();
                    $nuxt.$router.push("/");
                    location.reload();
                    return Promise.reject(error);
                  })
          }
      );
-4

Something that seems to be omitted in the chosen solution is: what happens if a request is triggered during the refresh? And why wait for a token to expire and a 401 response to get a new token?

1) refresh request is triggered

2) another request for a normal resource is triggered

3) refresh response received, token has changed (meaning old token is invalid)

4) Back-end process the request from step 2 but it received the old token => 401

Basically you will get 401 for all request fired during the refresh request (at least that is the issue I've been facing).

From this question Axios Request Interceptor wait until ajax call finishes and from @waleed-ali answer to this question it appears that request interceptors can return a Promise.

What my solution does is holding the requests and fire them right after the refresh request has been resolved.

In my vuex store User module (vuex + vuex-module-decorators):

  @Action({ rawError: true })
  public async Login(userInfo: { email: string, password: string }) {
    let { email, password } = userInfo
    email = email.trim()
    const { data } = await login({ email, password })
    setToken(data.access_token)
    setTokenExpireTime(Date.now() + data.expires_in * 1000)
    this.SET_TOKEN(data.access_token)
    // after getting a new token, set up the next refresh in 'expires_in' - 10 seconds
    console.log("You've just been logged-in, token will be refreshed in ", data.expires_in * 1000 - 10000, "ms")
    setTimeout(this.RefreshToken, data.expires_in * 1000 - 10000)
  }

  @Action
  public async RefreshToken() {
    setRefreshing(refresh().then(({ data }) => {
      setToken(data.access_token) // this calls a util function to set a cookie
      setTokenExpireTime(Date.now() + data.expires_in * 1000) // same here
      this.SET_TOKEN(data.access_token)
      // after getting a new token, set up the next refresh in 'expires_in' - 10 seconds
      console.log('Token refreshed, next refresh in ', data.expires_in * 1000 - 10000)
      setTimeout(this.RefreshToken, data.expires_in * 1000 - 10000)
      setRefreshing(Promise.resolve())
    }))
  }

In the Login action, I set up a timeout to call RefreshToken just before token will expire.

Same in the RefreshToken action, thus making a refresh loop which will automatically refresh the token before any 401 will ever take place.

The two important lines of the User module are:

setRefreshing(Promise.resolve())

When the refresh request is fulfilled then refreshing variable will instantly resolve.

And:

setRefreshing(refresh().then(({ data }) => {

this calls the refresh method of the api/user.ts file (which in turn calls axios) :

export const refresh = () =>
  request({
    url: '/users/login/refresh',
    method: 'post'
  })

and send the returned Promise into setRefreshing utility method in utils.ts:

let refreshing: Promise<any> = Promise.resolve()
export const getRefreshing = () => refreshing
export const setRefreshing = (refreshingPromise: Promise<any>) => { refreshing = refreshingPromise }

The refreshing variable holds a resolved Promise by default and will be set to the pending refresh request when it is fired.

Then in request.ts:

    service.interceptors.request.use(
  (config) => {
    if (config.url !== '/users/login/refresh') {
      return getRefreshing().then(() => {
        // Add Authorization header to every request, you can add other custom headers here
        if (UserModule.token) {
          console.log('changing token to:', UserModule.token)
          console.log('calling', config.url, 'now')
          config.headers['Authorization'] = 'Bearer ' + UserModule.token
        }
        return config
      })
    } else {
      return Promise.resolve(config)
    }
  },
  (error) => {
    Promise.reject(error)
  }
)

If the request is for the refresh endpoint we resolve it at once, if not we return the refreshing promise and chain it with what we want to do in the interceptor AFTER we get the updated token. If there are no refresh request currently pending then the promise is set to resolve instantly, if there is a refresh request then we'll wait for it to resolve and we'll be able to launch all other pending request with the new token.

Could be improved by just configuring the interceptor to ignore the refresh endpoint but I don't know how to do that yet.

2
  • 3
    I see what you mean, but it seems to me like you're actually dealing with something we haven't even discussed in this topic. The question has already been answered and I think there's no need to discuss the proper "business logic" behind the refreshing itself. In case you're interested, the question was asked specifically while I was building this library: github.com/Flyrell/axios-auth-refresh Aug 22, 2019 at 13:54
  • This was my first thought when I read this post. We have a lot of parallel calls and I don’t love the idea of spamming the token refresh calls when they happen. I’m still working through solutions, but came across async-mutex which might be exactly what I’m looking for if I can use it to stall all other async actions. Tbd
    – iamaword
    Oct 26, 2022 at 15:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.