Hi @Choudhary, Ashish ,you can use the acquireTokenSilent
method from the msal-browser
library to silently acquire a new token when the current one expires:
import { PublicClientApplication, EventType, EventMessage, AuthenticationResult } from '@azure/msal-browser';
import { msalConfig } from 'auth/authConfig';
export const msalInstance = new PublicClientApplication(msalConfig);
const accounts = msalInstance.getAllAccounts();
if (accounts.length > 0) {
const [{ idToken }] = accounts;
localStorage.setItem('authStatus', idToken);
msalInstance.setActiveAccount(accounts);
}
msalInstance.addEventCallback((event: EventMessage) => {
if (event.eventType === EventType.LOGIN_SUCCESS && event.payload) {
const payload = event.payload as AuthenticationResult;
const account = payload.account;
const { idToken } = account;
localStorage.setItem('authStatus', idToken);
msalInstance.setActiveAccount(account);
}
});
const refreshIdToken = async () => {
const accounts = msalInstance.getAllAccounts();
if (accounts.length > 0) {
const request = {
scopes: ["openid", "profile", "User.Read"],
account: accounts
};
try {
const response = await msalInstance.acquireTokenSilent(request);
localStorage.setItem('authStatus', response.idToken);
} catch (error) {
if (error instanceof InteractionRequiredAuthError) {
msalInstance.acquireTokenRedirect(request);
}
}
}
};
// Call refreshIdToken periodically or based on your application's needs
setInterval(refreshIdToken, 3600000); // Refresh token every hour
Please let me know if you have any questions and I can help you further.
If this answer helps you please mark "Accept Answer" so other users can reference it.
Thank you,
James