How reset the idToken when it expires?

Choudhary, Ashish 0 Reputation points
2024-09-13T08:59:27.99+00:00

I am working with ReactJs. I am using IdToken for backend api authentication. I am saving it in the localStorage and with every request I am sending it to the backend.

However in an hour the token expires and the backend api calls start failing.

and I want to refresh it either by reloading the page or silently. How can I do that?

Here is my code:
This is app.tsx

import { createBrowserRouter } from 'react-router-dom';
import App from 'App';
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[0]);
}

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);
	}
});

export const router = createBrowserRouter([
	{
		path: '/',
		element: 
Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
21,449 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. James Hamil 24,481 Reputation points Microsoft Employee
    2024-09-16T15:48:27.2933333+00:00

    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

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.