Azure B2C - MSAL callback method doesn't call the method which return the promise?

Viewed 456

In the Azure B2C in the authCallback() the ItWillCallPromise is not getting called. Is it as per the design or I am doing something wrong. Also, if its not possible as per the design is there a workaround to call the ItWillCallPromise method ?

function initializeAuthAgent() {
    var authConfig =  Config();

    authAgent = new Msal.UserAgentApplication({
        auth: {
            clientId: authConfig.clientId,
            authority: authConfig.authority,
            validateAuthority: false,
            postLogoutRedirectUri:  '/index.html'
        },
        cache: {
            cacheLocation: 'sessionStorage'
            
        }
    });

    authAgent.handleRedirectCallback(authCallback);


  authCallback(){
       ItWillCallPromise.then(function(ID){ console.log(ID)};
  }


  ItWillCallPromise =  function(){

 return fetch(url).then(function(a){ return a.ID;}

  }
2 Answers

Not sure if it's a typo in your code snippet. But as per that, it's not getting called because you are not calling :). () is missing.

ItWillCallPromise().then(function(ID){ console.log(ID)};

In MSAL.js v1, handleRedirectCallback will only be invoked when there is a hash response in the url (as a result of invoking loginRedirect or acquireTokenRedirect). Depending on the business logic of your app, you can first check if there is a hash in the url (before instantiating UserAgentApplication, which will clear the hash if one was present) and then check if a user is logged in, and then invoke ItWillCallPromise directly.

For example:

function initializeAuthAgent() {
    var authConfig =  Config();

    var hasHash = !!window.location.hash;

    authAgent = new Msal.UserAgentApplication({
        auth: {
            clientId: authConfig.clientId,
            authority: authConfig.authority,
            validateAuthority: false,
            postLogoutRedirectUri:  '/index.html'
        },
        cache: {
            cacheLocation: 'sessionStorage'
            
        }
    });

    var isLoggedIn = !!authAgent.getAccount();

    // If there is already a logged in user and were not returning from a redirect operation, immediately call ItWillCallPromise.
    if (isLoggedIn && !hasHash) {
      ItWillCallPromise()
    }

    authAgent.handleRedirectCallback(authCallback);

    


  authCallback(){
       ItWillCallPromise.then(function(ID){ console.log(ID)};
  }


  ItWillCallPromise =  function(){

 return fetch(url).then(function(a){ return a.ID;}

  }

MSAL.js v2 (aka @azure/msal-browser on npm) makes this easier, as handleRedirectPromise (which replaces handleRedirectCallback) is invoked on every page load. More details: https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/v1-migration.md

Related