I am using reactjs, mbox and axios and ran into a problem. I have a api that gives out an access token and a refresh token. The access token dies every 20mins and when this happens the server sends a 401 back and my code will automatically send the refresh token out to get a new access token.
Once a new access token is granted that same rejected request will be sent again. Now my code works great until I throw multiple rejects that pretty much could fire all at the same time.
So first request goes off, a 401 is sent back and it gets a new refresh token, well all the other requests will be trying to do the same thing but the other requests will now fail because the refresh token will be used and a new one will be issued to the first request.
This will kick off my code to redirect the user to the login page.
So essentially I am stuck of only have 1 request at a time.
export const axiosInstance = axios.create({
baseURL: getBaseUrl(),
timeout: 5000,
contentType: "application/json",
Authorization: getAuthToken()
});
export function updateAuthInstant() {
axiosInstance.defaults.headers.common["Authorization"] = getAuthToken();
}
function getAuthToken() {
if (localStorage.getItem("authentication")) {
const auth = JSON.parse(localStorage.getItem("authentication"));
return `Bearer ${auth.accessToken}`;
}
}
axiosInstance.interceptors.response.use(
function(response) {
return response;
},
function(error) {
const originalRequest = error.config;
if (error.code != "ECONNABORTED" && error.response.status === 401) {
if (!originalRequest._retry) {
originalRequest._retry = true;
return axiosInstance
.post("/tokens/auth", {
refreshToken: getRefreshToken(),
grantType: "refresh_token",
clientId : "myclient"
})
.then(response => {
uiStores.authenticaionUiStore.setAuthentication(JSON.stringify(response.data))
updateAuthInstant();
return axiosInstance(originalRequest);
});
} else {
uiStores.authenticaionUiStore.logout();
browserHistory.push({ pathname: '/login',});
}
}
return Promise.reject(error);
}
);
Edit
I am having problem that the code I Need to check to resetup authentication is not working when a user copies in a direct url
app.js
<React.Fragment>
<Switch>
<Route path="/members" component={MemberAreaComponent} />
</Switch>
</React.Fragment >
In memberAreaComponent
<Route path="/members/home" component={MembersHomeComponent} />
When I type in http://www.mywebsite/members/home
MembersHomeComponent - componentDidMount runs first
MemberAreaComponent - componentDidMount runs second
AppCoontainer = componentDidMount runs last.