For my site, I added a simple authorization page through microsoft (using the @azure/msal-react library). You can check out the demo version at the link https://codesandbox.io/s/wizardly-williams-j4bo42
After successful registration, the user is redirected to the site.
I'm satisfied with the job. But the problem is that the access token received during authorization lives only for one hour. Tell me how can I make it so that the access token is updated automatically.
In one of our most recent react apps we made use of an AxiosInterceptor component that is designed to handle HTTP response errors and automatically attempt a token refresh in case of 403 Unauthorized errors.
When an axios request receives a response, the interceptor checks if there is an error. If there is no error, it simply returns the response.
If the error code exists and the original request was not for the /auth/login endpoint, it checks if the response status is 403 Unauthorized and if the request hasn't already been retried.
In case of 403, if the Authorization header of the original request equals the stored access token, it sets the Authorization header to the stored refresh token and attempts to refresh the tokens using the refreshTokenServices function.
If the token refresh fails, or the Authorization header of the original request does not equal the stored access token, it redirects the user to the login page with an error message.
The code would look something like this:
// Response interceptor for API calls
axiosApiInstance.interceptors.response.use((response) => {
return response
}, async function (error) {
const originalRequest = error.config;
if (error.response.status === 403 && !originalRequest._retry) {
originalRequest._retry = true;
const access_token = await refreshAccessToken();
axios.defaults.headers.common['Authorization'] = 'Bearer ' + access_token;
return axiosApiInstance(originalRequest);
}
return Promise.reject(error);
});
Here is a great article about this:
https://thedutchlab.com/blog/using-axios-interceptors-for-refreshing-your-api-token
The simplest approach (but not the most ideal) could be this:
You have a thing called refresh token which you use when you want to get a new access token. You can store this token somewhere (maybe in localStorage or environment variable or such).
Now when the API says that the access token is expired, you fetch the new access token by calling the /refresh endpoint (this could be something else too in your case). Generally this API needs a refresh token in payload which you already have stored in your application.
You will get a fresh access token. And when that expires, you do the same thing again.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With