Token authentication is being implemented in my application. The access token
expires after a certain time and is then refreshed using a refresh token
.
Axios is used for API calls, with an interceptor set up to handle 401
responses:
axios.interceptors.response.use(undefined, function (err) {
if (err.status === 401 && err.config && !err.config.__isRetryRequest) {
serviceRefreshLogin(
getRefreshToken(),
success => { setTokens(success.access_token, success.refresh_token) },
error => { console.log('Refresh login error: ', error) }
)
err.config.__isRetryRequest = true
err.config.headers.Authorization = 'Bearer ' + getAccessToken()
return axios(err.config);
}
throw err
})
When a 401 response is intercepted, a login is performed along with retrying the original failed request using the fresh tokens. However, there seems to be an issue where the retry happens with the old expired credentials as the then
block of serviceRefreshLogin
executes later than the getAccessToken()
in the interceptor.
The functions getAccessToken()
and getRefreshToken()
retrieve the stored tokens from the browser's storage mechanisms such as localStorage or cookies.
What steps can be taken to ensure that statements are executed only after a promise returns successfully?
(For more context, refer to this Github issue: https://github.com/mzabriskie/axios/issues/266)