use msal to connect to Azure B2C - state parameter

Viewed 2559
3 Answers

I use state in my loginRedirect() method.. so I'll post my code here which should help you enough to make this work. I'm using MSAL in angular but the methods that I call should be the same.

In this example user clicks on a login button which calls a login method:

{
   const args: AuthenticationParameters = {
     state: "some string" //set state parameter (type: string)
   };
   this.msalService.loginRedirect(args);
}

This code will then redirect user to login.. and then back to your website (your redirectURI).. On this page you should implement handleRedirectCallback method which will be triggered after user is redirected. In this callback you will also get a response (or error) from login process which will include your state string.

this.msalService.handleRedirectCallback((authError, response) => {
  if (response) {
     const state = this.msalService.getAccountState(response.accountState);
     // you don't need to use "this.msalService.getAccountState()" I think
     ...
     do something with state. I use it to redirect back to initial page url. 
     ...
  }
});

You can send the state parameter on the loginRequest:

const loginRequest = {
   ...
    scopes: "your scopes",
    state: "my custom state value"
}

Then you capture it in the response on accountState, like this:

clientApplication.loginPopup(loginRequest).then(function (loginResponse) {
    if (loginResponse.account) {
        // will print: my custom state value
        console.log(loginResponse.accountState);
        ....
    }
});

You can find the documentation here: https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-js-pass-custom-state-authentication-request

Related