Hello @Vadym S
Welcome to Micrsoft QnA!
Method 1
- Authentication Flow: When a user successfully authenticates (signs in), MSAL stores the refresh token internally.
- Acquire Token Silent: After the initial login, use
acquireTokenSilent
to get a new access token. MSAL will automatically use the refresh token (if needed) to obtain a fresh access token behind the scenes. Here's an example:
JavaScript
import { InteractionRequiredAuthError } from "@azure/msal-browser";
import { msalInstance } from "./authConfig";
async function acquireToken() {
const accounts = msalInstance.getAllAccounts();
if (!accounts || accounts.length === 0) {
throw new Error("No user account found");
}
const request = {
scopes: ["User.Read", "Mail.Read"], // Include the scopes you need
account: accounts[0], // Assuming you only have one user
};
try {
const response = await msalInstance.acquireTokenSilent(request);
const accessToken = response.accessToken;
// Extract Refresh Token Here:
const refreshToken = response.refreshToken; // If available
// You can store the refresh token and the refreshOn time.
// Store your tokens
if (refreshToken) localStorage.setItem("refreshToken", refreshToken);
// Set refreshOn time
const now = new Date();
const refreshOn = new Date(now.getTime() + 1000 * response.expiresIn);
localStorage.setItem("refreshOn", refreshOn);
return accessToken;
} catch (error) {
if (error instanceof InteractionRequiredAuthError) {
// Trigger interactive authentication (login)
msalInstance.acquireTokenRedirect(request);
} else {
throw error;
}
}
}
Refresh Token Storage: You can extract the refresh token and refreshOn time. Store these securely (e.g., encrypted in localStorage or using a more robust storage mechanism).
OR Method 2 :
Manual Refresh Flow
- Check Refresh Time: Before each API call, compare the current time with the stored
refreshOn
time. If it's time to refresh, proceed. - Acquire Token with Refresh Token: Use MSAL's
acquireTokenByRefreshToken
method, passing in the stored refresh token to get a new access token.
Example: Refreshing Token
JavaScript
async function refreshToken() {
const refreshToken = localStorage.getItem("refreshToken");
if (!refreshToken) {
throw new Error("Refresh token not found");
}
const response = await msalInstance.acquireTokenByRefreshToken({
refreshToken,
scopes: ["User.Read", "Mail.Read"],
});
const newAccessToken = response.accessToken;
// Store the new access token
localStorage.setItem("accessToken", newAccessToken);
// Set the new refreshOn time
const now = new Date();
const refreshOn = new Date(now.getTime() + 1000 * response.expiresIn);
localStorage.setItem("refreshOn", refreshOn);
return newAccessToken;
}
These are examples you may need to adjust so your Application can work ! !
--
I hope this helps!
Kindly mark the answer as Accepted and Upvote in case it helped!
Regards