score:19

Accepted answer
msalinstance.loginredirect(loginrequest);

the piece of code above does next:

  1. looks into session storage for key msal.[clientid].interaction.status and other temp values required for redirection process. if such key exist and its value equals 'interaction_in_progress' error will be thrown.
  2. creates entry in session storage msal.[clientid].interaction.status = interaction.status
  3. redirects user to auth-page.

in case of successful login user will be redirected to initial page with your code and go through 1-3 steps and will catch an error;

the piece of code below removes all temp values in session storage and completes auth redirection flow but it is async and never will be completed.

   msalinstance.handleredirectpromise()
    .then(res=>{
      console.log(res)
    })
    .catch(err => {
      console.error(err);
    });

the solution will be

// account selection logic is app dependent. adjust as needed for different use cases.
// set active acccount on page load
const accounts = msalinstance.getallaccounts();
if (accounts.length > 0) {
  msalinstance.setactiveaccount(accounts[0]);
}

msalinstance.addeventcallback((event) => {
  // set active account after redirect
  if (event.eventtype === eventtype.login_success && event.payload.account) {
    const account = event.payload.account;
    msalinstance.setactiveaccount(account);
  }
}, error=>{
  console.log('error', error);
});

console.log('get active account', msalinstance.getactiveaccount());

// handle auth redired/do all initial setup for msal
msalinstance.handleredirectpromise().then(authresult=>{
  // check if user signed in 
  const account = msalinstance.getactiveaccount();
  if(!account){
    // redirect anonymous user to login page 
    msalinstance.loginredirect();
  }
}).catch(err=>{
  // todo: handle errors
  console.log(err);
});

score:-1

this may not be a clean solution. but this does work at least in vue.js.

next to your acquiretoken() logic, add this

// check local or session storage which may have already contain key 
// that partially matches your azure ad client id
let havekeys = object.keys(localstorage).tostring().includes('clientid')
// that error will just go away when you refrest just once
let justonce = localstorage.getitem("justonce");

if (havekeys && !justonce) {
  localstorage.setitem("justonce", "true");
  window.location.reload();
} else {
  localstorage.removeitem("justonce")
}

score:0

i have found that in msal.js v2 you can check interaction status in vanilla .js code to see if there is an interaction in progress, should you need to do this for some reason:

const publicclientapplication = new window.msal.publicclientapplication(msalconfig);

var clientstring = "msal." + msalconfig.clientid + ".interaction.status";

var interaction-status = publicclientapplication.browserstorage.temporarycachestorage.windowstorage[clientstring]

score:0

you can clear the browser storage before open the loginpopup:

let msalinstance: publicclientapplication = this._msauthservice.instance as publicclientapplication;
msalinstance["browserstorage"].clear();

score:0

update @azure/msal-browser@2.21.0.

score:3

during development, it is possible that you left the sign-in flow in a progress-state due to a coding issue that you will need to correct. you can clear the immediate problem by deleting the msal.interaction.status cookie from the browser. of course, if this problem persists, then you need to correct the problem using one of the other solutions suggested on this page.

score:5

i believe this is the correct answer and way to set this up. others here led me to clues to solve this.

tldr; set your code up like this:

// authredir.ts  (or authredir.vue inside mounted())
await msalinstance.handleredirectpromise();

// mysigninpage.ts (or userprofile.vue, or whatever page invokes a sign-in)
await msalinstance.handleredirectpromise();

async signin(){
  const loginrequest: msal.redirectrequest = {
    scopes: ["openid", "profile", "offline_access","your_other_scopes"]
    redirecturi: "http://localhost:8080/authredirect"
        };

  const accounts = msalinstance.getallaccounts();
  if (accounts.length === 0) {

    await msalinstance.loginredirect();
  }
}

if you do this correctly, you wont need the code @shevchenko-vladislav shared, wherein setactiveaccount() has to be manually done by you. remember to verify all async/await wherever you call this in your app! and notice how i did not use handleredirectpromise().then() or anything, really, in my main authredirect.vue file. just handleredirectpromise() on load.

other solutions on stackoverflow suggest things like checking for and deleting the interaction state from the session. um, no! if you have that state left over after a sign-in, it means the process wasn't done right! msal cleans itself up!

full details:

it is super important to understand what msal is actually doing during it's entire lifecycle (especially the redir path as opposed to popup), and sadly the docs fail to do a good job. i found this little "side note" extremely, extremely important:

https://github.com/azuread/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/errors.md#interaction_in_progress

"if you are calling loginredirect or acquiretokenredirect from a page that is not your redirecturi you will need to ensure handleredirectpromise is called and awaited on both the redirecturi page as well as the page that you initiated the redirect from. this is because the redirecturi page will initiate a redirect back to the page that originally invoked loginredirect and that page will process the token response."

in other words, both your redirect page and the page that invoked the sign-in request must call handleredirectpromise() on page load (or on mounted(), in my case, since i am using vue)

in my case, i have this:

  • http://localhost:8080/authredirect *
  • http://localhost:8080/userprofile

*only my authredirect uri needs to be registered as a redirecturi with my app registration in azure ad.

so here is the loginredirect() lifecycle, which i had no idea, and lost a days work sorting out:

  1. /userprofile (or some page) invokes a sign-in request
  2. the request calls handleredirectpromise() (which sets msal up with info about where the request was made and the interaction state that will bite you later if you dont complete the process)
  3. and then calls loginredirect(loginrequest)
  4. -> user is redirected, completes sign-in
  5. azure redir back to -> /authredirect
  6. /authredirect invokes handleredirectpromise(), which forwards along to -> /userprofile
  7. /userprofile invokes handleredirectpromise() which does the actual processing of tokens and internally calls setactiveaccount() to save your user to session.

dang. that was fun. and not explained in the docs at all.

so, the reason you are getting the interaction-in-progress error is because you are thinking you're all done on step 6. nope! step 7 is where that interaction_in_progress state gets settled and cleaned up so that subsequent calls wont trip up on it!!

final thought:

if you have a designated sign-in page you want users to always start/finish from (and itself is the registered redirect uri), i suppose these steps will be reduced (no forwarding like in step 6 here). in my case, i want the user redirected back to wherever they might have gotten bumped out of due to a session expiration. so i just found it easier to call handleredirectpromise() on every single page load everywhere, in case said page it needs to finalize authentication. or, i could build my own redirect logic into a dedicated sign-in page that can put the user back where they were prior to hitting it. it's just that as for msal, i had no idea the process was finishing up on the requesting page rather than contained within my authredirect page, and that is what bit me.

now, if we could just get ms to provide far better docs on the delicate and critical nature of msal, and to provide a vue plugin (why does only angular and react get all the glory? :) ), that would be great!


Related Query

More Query from same tag