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
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.
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.
Share Improve this question asked Jun 2, 2023 at 9:02 PaulPaul 23315 silver badges41 bronze badges 5- Are you using custom policy for azure ad b2c ? – Shubham Dixit Commented Jun 4, 2023 at 11:24
- 1 If you want a usable answer you need to provide more details on how your tokens are issued as well as other parameters for what you would want token and refresh token lifetimes to be. Right now an acceptable answer to your question would be "remove the expiration time". – possum Commented Jun 4, 2023 at 13:35
- @Shubham Dixit I don't quite understand what you are asking, but I did connect my SPA to azure with the help of this tutorial learn.microsoft./en-us/azure/active-directory/develop/… – Paul Commented Jun 4, 2023 at 13:59
- I can help you with the flow ,but you need to tell me more details .Are you using azure active directory b2c and what you are trying to achieve in terms of application structure – Shubham Dixit Commented Jun 5, 2023 at 4:41
- @Shubham Dixit Yes, I found out more details (sorry for the wait). We just use Azure AD. In terms of the structure of the application, I need it to be automatically updated after the time of the token has expired (since now I have the receipt of the token attached to the SignInButton button) – Paul Commented Jun 5, 2023 at 7:55
3 Answers
Reset to default 6 +50In one of our most recent react apps we made use of an AxiosInterceptor
ponent 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.mon['Authorization'] = 'Bearer ' + access_token;
return axiosApiInstance(originalRequest);
}
return Promise.reject(error);
});
Here is a great article about this:
https://thedutchlab./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.
You could do something like this:
MSAL (Microsoft Authentication Library) for JavaScript supports the OAuth 2.0 Authorization Code Flow with PKCE, which inherently uses refresh tokens to maintain user's session.
The details of using refresh tokens are abstracted away by the library for you. When you perform an acquireTokenSilent operation, if the access token in the cache has expired and a valid refresh token exists, MSAL will use that refresh token to obtain a new access token and refresh token pair silently. This is done automatically by the library and requires no additional code from your end. If a valid refresh token does not exist, an error is thrown and you must then handle this by making an interactive request to obtain a new token.
An example:
import { PublicClientApplication } from "@azure/msal-browser";
const myMSALObj = new PublicClientApplication(msalConfig);
function getTokenRedirect(request) {
return myMSALObj.acquireTokenSilent(request)
.catch(error => {
// Could also check if error instance of InteractionRequiredAuthError if you'd like to be more specific
if (error instanceof InteractionRequiredAuthError) {
// fallback to interaction when silent call fails
return myMSALObj.acquireTokenRedirect(request)
} else {
console.error(error);
}
});
}
// Call getTokenRedirect where you need it, for example:
// This is an example. Replace it with the API you want to call
const callMSGraph = async () => {
const tokenResponse = await getTokenRedirect(loginRequest);
const accessToken = tokenResponse.accessToken;
// Use this accessToken to call the Graph API or any other API
}
Silent token acquisition:
Silent token acquisition in MSAL
Refresh tokens in OAuth 2.0:
Refresh Tokens