How to force refresh id_token from B2C with msal.js and react js

Viewed 2293

I'm using msal.js in my react project for authentication. In that, I have a profile edit option.

steps in profile edit

  1. Update the database
  2. Update B2C profile name with Graph API

So once I edit the name, the B2C profile name is updated. But not the id_token. I wanna force refresh the id_token form B2C. The acquireTokenSilent method is always fetching the token from the cache. Is there any way to force the application to get the new token from B2C?

here is my code for acquireTokenSilent method

async acquireToken(request, redirect) {
      return msalApp
        .acquireTokenSilent(request)
        .then((loginResponse) => {
          console.log('gg');
          if (loginResponse) {
            console.log(loginResponse);
            this.setState({
              account: loginResponse.account,
              isAuthenticated: true,
              error: null,
            });
            return true;
          }
        })
        .catch((error) => {
          // Call acquireTokenPopup (popup window) in case of acquireTokenSilent failure
          // due to consent or interaction required ONLY
          if (requiresInteraction(error.errorCode)) {
            this.setState({
              isAuthenticated: false,
            });
            return redirect ? msalApp.acquireTokenRedirect(request) : this.onSignIn(redirect);
          }
          console.error('Non-interactive error:', error.errorCode);
          return false;
        });
    }
3 Answers

Check out method definition in MSAL.js for the acquireTokenSilent method: https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-core/src/UserAgentApplication.ts#L667

/**
 * Use this function to obtain a token before every call to the API / resource provider
 *
 * MSAL return's a cached token when available
 * Or it send's a request to the STS to obtain a new token using a hidden iframe.
 *
 * @param {@link AuthenticationParameters}
 *
 * To renew idToken, please pass clientId as the only scope in the Authentication Parameters
 * @returns {Promise.<AuthResponse>} - a promise that is fulfilled when this function has completed, or rejected if an error was raised. Returns the {@link AuthResponse} object
 *
 */
acquireTokenSilent(userRequest: AuthenticationParameters): Promise<AuthResponse> {

Since you are not using profile edit policy from B2C, this is the consequence. You’ll only get a new token with acquireTokenSilent if the msal objects from the session storage are cleared, otherwise until the token in the session storage has expired, it’s acting as the cache.

A bit of a late reply, but the request object passed in acquireTokenSilent(request) can have a forceRefresh boolean property which, according to the docs, forces silent requests to make network calls if true.

Related