reactjsazure-active-directoryazure-ad-msalmsal.jsreact-aad-msal

How to maintain the IdToken after page reload in MSAL React App?


I am using MSAL in React App. After the sign-in, I am getting the details using this code-

const [userDetails, setUserDetails] = useState(null);

useEffect(() => {

    instance

      .handleRedirectPromise()

      .then(() => {

        const currentUser = instance.getAllAccounts()[0];

        setUserDetails(currentUser);

      })

      .catch((error) => console.log(error));

  }, []);

In the first load, I am getting these details in the const userDetails-

{

    "homeAccountId": "XX-X553252fedd35",

    "environment": "login.XX.net",

    "tenantId": "XX-63c7-XX-91c6-553252fedd35",

    "username": "X@XX.XX.com",

    "localAccountId": "XX-7e21-4730-XX-XX",

    "name": "XX XX",

    "idToken": "xcasdcasdf3adsfa4sdafsd43fadsf43asdfxx"

    "idTokenClaims": {

     XXXX: XXXX

    }
}

Before Reload-

ScreenShot

But when I reload the page, the IdToken got missing from this userDetails const.

And in the console, I got this log message after reloading-

@azure/msal-common@12.0.0 : Info - CacheManager:getIdToken - No token found

After Reload-

ScreenShot

I am using these npm packages-

  "@azure/msal-browser": "^2.34.0",
  "@azure/msal-react": "^1.5.4",

I need to have the idToken for JWT authentication.


Solution

  • You can access the token by calling acquireTokenSilent:

    instance.acquireTokenSilent(tokenRequest)
        .then((response) => {
          // Handle the successful acquisition of a new token
          // ...
          console.log(response);
        })
        .catch((error) => {
          // Handle any errors that occur during token acquisition
          // ...
        });  
    
     
    

    tokenRequest example:

    const tokenRequest = {
        scopes: ["openid"],
      };