Created
May 22, 2020 14:22
-
-
Save arvindkumarbadwal/379f616ca4a3f39b9224189c91af562f to your computer and use it in GitHub Desktop.
Axios interceptors for token refreshing with multipe async api support
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
import axios from 'axios'; | |
import { Auth } from '.'; | |
let isRefreshing = false; | |
let refreshSubscribers = []; | |
axios.interceptors.response.use(response => { | |
return response; | |
}, error => { | |
const originalReq = error.config; | |
// refersh acess token | |
if(error.response.status === 401 && originalReq.config) { | |
if(!isRefreshing) { | |
isRefreshing = true; | |
callRefreshTokenAPI() | |
.then((response) => { | |
Auth.setAuthToken(response.data) // set access_token & refersh_token | |
isRefreshing = false; | |
onRefreshed(response.data.access_token); | |
refreshSubscribers = []; | |
}) | |
} | |
return new Promise((resolve) => { | |
subscribeTokenRefresh(token => { | |
// replace the expired token and retry | |
originalReq.headers['Authorization'] = 'Bearer ' + token; | |
resolve(axios(originalReq)); | |
}) | |
}) | |
} else { | |
return Promise.reject(error); | |
} | |
}); | |
subscribeTokenRefresh(cb) { | |
refreshSubscribers.push(cb); | |
} | |
onRefreshed(token) { | |
refreshSubscribers.map(cb => cb(token)); | |
} | |
callRefreshTokenAPI() { | |
let access_token = Auth.getAccessToken(); | |
const requestOptions = { | |
headers: { | |
'Content-Type': 'application/json', | |
'Accept': 'application/json', | |
'Authorization' => 'Bearer ' + access_token | |
}, | |
}; | |
const body = JSON.stringify({ | |
refresh_token: refresh_token | |
}); | |
return axios.post('http://localhost:8080/api/v1/refresh-token', body, requestOptions); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment