msal/angular reloads page mulitple times

57 Views Asked by At

I'm facing an issue where MSAL is reloading the page multiple times trying to get an authentication token. I'm using the below APP_INITIALIZER to handle the authentication. When I clear all the tokens out and start at a fresh page load, I get this sequence in the output.

  1. Navigated to http://localhost:4200/myPage
    • Console shows: initialize, handleRedirectPromise, getAllAccounts
  2. Navigated to the login.microsoftonline.com page
  3. Navigated to http://localhost:4200
    • Console shows: initialize, handleRedirectPromise
  4. Navigated to http://localhost:4200/myPage
    • Console shows: initialize, handleRedirectPromise
    • Console then shows two acquireTokenSilent rejected with error messages
    • Console then shows setActiveAccount, initialize, handleRedirectPromise
  5. Navigated to http://localhost:4200
    • I assume the initialize/handleRedirectPromise previous are from this and just out of order.
  6. Navigated to http://localhost:4200/myPage
    • Console shows: initialize, handleRedirectPromise, setActiveAccount

Why are steps three, four and five happening?

export const provideAzure = () => makeEnvironmentProviders([
    {
        provide: APP_INITIALIZER,
        useFactory: (msalService: MsalService, msalBroadcastService: MsalBroadcastService) => async () => {
            console.info('initialize')
            await publicClientApplication.initialize()

            console.info('handleRedirectPromise')
            const redirect = await msalService.instance.handleRedirectPromise()

            if (redirect?.account) {
                console.info('setActiveAccount')
                msalService.instance.setActiveAccount(redirect.account)
            } else {
                console.info('getAllAccounts')
                const accounts = msalService.instance.getAllAccounts()

                if (accounts.length > 0) {
                    console.info('setActiveAccount')
                    msalService.instance.setActiveAccount(accounts[0])
                }
            }
        },
        multi: true,
        deps: [MsalService, MsalBroadcastService]
    },
    {provide: HTTP_INTERCEPTORS, useClass: MsalInterceptor, multi: true},
    MsalService,
    MsalGuard
])

I'm using @azure/msal-angular 3.0.4 and @azure/msal-browser 3.10.0 with Angular 16.1.2

0

There are 0 best solutions below