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

1k Views Asked by At

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": "[email protected]",

    "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/[email protected] : 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.

2

There are 2 best solutions below

0
cfx_p On BEST ANSWER

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"],
  };
0
Musadiq Khan On

Why do not you save the token in localStorage. So, you can preserve it even on refresh?