Forked from Godofbrowser/axios.refresh_token.1.js
Last active
October 27, 2021 03:17
-
-
Save gogones/a10a1cb877acf71af72de08d2860219b to your computer and use it in GitHub Desktop.
Axios interceptor for refresh token when you have multiple parallel requests. Demo implementation: https://github.com/Godofbrowser/axios-refresh-multiple-request
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// for multiple requests | |
let isRefreshing = false; | |
let failedQueue = []; | |
const processQueue = (error, token = null) => { | |
failedQueue.forEach(prom => { | |
if (error) { | |
prom.reject(error); | |
} else { | |
prom.resolve(token); | |
} | |
}) | |
failedQueue = []; | |
} | |
axios.interceptors.response.use(function (response) { | |
return response; | |
}, function (error) { | |
const originalRequest = error.config; | |
if (error.response.status === 401 && !originalRequest._retry) { | |
if (isRefreshing) { | |
return new Promise(function(resolve, reject) { | |
failedQueue.push({resolve, reject}) | |
}).then(token => { | |
originalRequest.headers['Authorization'] = 'Bearer ' + token; | |
return axios(originalRequest); | |
}).catch(err => { | |
return Promise.reject(err); | |
}) | |
} | |
originalRequest._retry = true; | |
isRefreshing = true; | |
const refreshToken = window.localStorage.getItem('refreshToken'); | |
return new Promise(function (resolve, reject) { | |
axios.post('http://localhost:8000/auth/refresh', { refreshToken }) | |
.then(({data}) => { | |
window.localStorage.setItem('token', data.token); | |
window.localStorage.setItem('refreshToken', data.refreshToken); | |
axios.defaults.headers.common['Authorization'] = 'Bearer ' + data.token; | |
originalRequest.headers['Authorization'] = 'Bearer ' + data.token; | |
processQueue(null, data.token); | |
resolve(axios(originalRequest)); | |
}) | |
.catch((err) => { | |
processQueue(err, null); | |
reject(err); | |
}) | |
.finally(() => { isRefreshing = false }) | |
}) | |
} | |
return Promise.reject(error); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Intercept and refresh expired tokens for multiple requests (same implementation but with some abstractions) | |
// | |
// HOW TO USE: | |
// import applyAppTokenRefreshInterceptor from 'axios.refresh_token.2.js'; | |
// import axios from 'axios'; | |
// ... | |
// applyAppTokenRefreshInterceptor(axios); // register the interceptor with all axios instance | |
// ... | |
// - Alternatively: | |
// const apiClient = axios.create({baseUrl: 'example.com/api'}); | |
// applyAppTokenRefreshInterceptor(apiClient); // register the interceptor with one specific axios instance | |
// ... | |
// - With custom options: | |
// applyAppTokenRefreshInterceptor(apiClient, { | |
// shouldIntercept: (error) => { | |
// return error.response.data.errorCode === 'EXPIRED_ACCESS_TOKEN'; | |
// } | |
// ); // register the interceptor with one specific axios instance | |
// | |
// PS: You may need to figure out some minor things yourself as this is just a proof of concept and not a tutorial. | |
// Forgive me in advance | |
const shouldIntercept = (error) => { | |
try { | |
return error.response.status === 401 | |
} catch (e) { | |
return false; | |
} | |
}; | |
const setTokenData = (tokenData = {}, axiosClient) => { | |
// If necessary: save to storage | |
// tokenData's content includes data from handleTokenRefresh(): { | |
// idToken: data.auth_token, | |
// refreshToken: data.refresh_token, | |
// expiresAt: data.expires_in, | |
// }; | |
}; | |
const handleTokenRefresh = () => { | |
const refreshToken = window.localStorage.getItem('refreshToken'); | |
return new Promise((resolve, reject) => { | |
axios.post('http://localhost:8000/auth/refresh', { refreshToken }) | |
.then(({data}) => { | |
const tokenData = { | |
idToken: data.auth_token, | |
refreshToken: data.refresh_token, | |
expiresAt: data.expires_at, | |
}; | |
resolve(tokenData); | |
}) | |
.catch((err) => { | |
reject(err); | |
}) | |
}); | |
}; | |
const attachTokenToRequest = (request, token) => { | |
request.headers['Authorization'] = 'Bearer ' + token; | |
// If there is an edge case where access token is also set in request query, | |
// this is also a nice place to add it | |
// Example: /orders?token=xyz-old-token | |
if (/\/orders/.test(request.url)) { | |
request.params.token = token; | |
} | |
}; | |
export default (axiosClient, customOptions = {}) => { | |
let isRefreshing = false; | |
let failedQueue = []; | |
const options = { | |
attachTokenToRequest, | |
handleTokenRefresh, | |
setTokenData, | |
shouldIntercept, | |
...customOptions, | |
}; | |
const processQueue = (error, token = null) => { | |
failedQueue.forEach(prom => { | |
if (error) { | |
prom.reject(error); | |
} else { | |
prom.resolve(token); | |
} | |
}); | |
failedQueue = []; | |
}; | |
const interceptor = (error) => { | |
if (!options.shouldIntercept(error)) { | |
return Promise.reject(error); | |
} | |
if (error.config._retry || error.config._queued) { | |
return Promise.reject(error); | |
} | |
const originalRequest = error.config; | |
if (isRefreshing) { | |
return new Promise(function (resolve, reject) { | |
failedQueue.push({resolve, reject}) | |
}).then(token => { | |
originalRequest._queued = true; | |
options.attachTokenToRequest(originalRequest, token); | |
return axiosClient.request(originalRequest); | |
}).catch(err => { | |
return Promise.reject(error); // Ignore refresh token request's "err" and return actual "error" for the original request | |
}) | |
} | |
originalRequest._retry = true; | |
isRefreshing = true; | |
return new Promise((resolve, reject) => { | |
options.handleTokenRefresh.call(options.handleTokenRefresh) | |
.then((tokenData) => { | |
options.setTokenData(tokenData, axiosClient); | |
options.attachTokenToRequest(originalRequest, tokenData.idToken); | |
processQueue(null, tokenData.idToken); | |
resolve(axiosClient.request(originalRequest)); | |
}) | |
.catch((err) => { | |
processQueue(err, null); | |
reject(err); | |
}) | |
.finally(() => { | |
isRefreshing = false; | |
}) | |
}); | |
}; | |
axiosClient.interceptors.response.use(undefined, interceptor); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* eslint-disable no-underscore-dangle */ | |
/* eslint-disable no-param-reassign */ | |
/* eslint-disable fp/no-mutation */ | |
import * as axios from 'axios'; | |
import {BASE_API_UMS} from 'constants/baseApi'; | |
import {clientIdData, updateLocalTokenResponse} from 'utils/userLocalService'; | |
import {history} from 'configure-store'; | |
import {PORTAL} from '../constants/routes'; | |
export default class ApiConfig { | |
constructor() { | |
this.timeout = 310000; | |
this.instance = axios.create({ | |
baseURL: process.env.REACT_APP_API_URL, | |
headers: { | |
Accept: 'application/json', | |
'Content-Type': 'application/json', | |
'Ocp-Apim-Subscription-Key': process.env.REACT_APP_API_CLIENT_ID, | |
}, | |
}); | |
} | |
init = () => { | |
this.instance.interceptors.request.use( | |
config => { | |
const token = clientIdData().accessToken; | |
if (token) { | |
config.headers.Authorization = `Bearer ${token}`; | |
} | |
return config; | |
}, | |
error => Promise.reject(error) | |
); | |
this.instance.interceptors.response.use( | |
res => res, | |
async err => { | |
const originalConfig = err.config; | |
// Refresh Token is invalid | |
if ( | |
err.response.status === 400 && | |
originalConfig.url === | |
`${BASE_API_UMS}/refreshtoken/${process.env.REACT_APP_CLIENT_ID}` | |
) { | |
history.push(PORTAL); | |
} | |
// Access Token was expired | |
if (err.response.status === 401 && !originalConfig._retry) { | |
originalConfig._retry = true; | |
try { | |
const rs = await this.instance.post( | |
`${BASE_API_UMS}/refreshtoken/${process.env.REACT_APP_CLIENT_ID}`, | |
{ | |
refreshToken: clientIdData().refreshToken, | |
} | |
); | |
const tokenResponse = rs.data; | |
updateLocalTokenResponse(tokenResponse); | |
return this.instance(originalConfig); | |
} catch (_error) { | |
return Promise.reject(_error); | |
} | |
} | |
return Promise.reject(err); | |
} | |
); | |
return this.instance; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment