Reputation: 1018
I want to implement JWT authentication in a react app using Axios.
There are many solutions using axios.interceptors
that fetch the token again if the request failed due to the authentication error.
Example:
axios.interceptors.response.use(function(response) {
return response;
},function(error) {
const originalReq = error.config;
if ( error.response.status == 401 &&
!originalReq._retry &&
error.response.config.url != URL_USER_AUTHENTICATE ) {
originalReq._retry = true;
return axios.post(BASE_URL+URL_REFRESH_TOKEN,{})
.then((res) =>{
if ( res.data.status == "success") {
return axios(originalReq);
}
}).catch((error) => {window.location.href="/logout/nosession"});
}
return Promise.reject(error);
});
However, it doesn't work if we have parallel requests. Imagine that we have two parallel requests, so both will request the new authentication token.
Does anybody know any fix?
Upvotes: 3
Views: 3134
Reputation: 29208
My example React SPA has some code that manages this, and may give you some ideas for your own solution. The third class below uses a technique of handling a list of promises but only making the remote call on one of them, then returning the same result to all callers.
An alternatiive solution can be to do a silent refresh in a background timer when the token is close to expiry, based on the expires_in
field returned with the access token. But that is not fully reliable since 401s can occur for multiple reasons, eg due to some types of infrastructure or server key changes, so I have always written 401 handling in clients, to ensure reliability.
Upvotes: 2