Search code examples
angularazure-ad-msaladalmsal.jsmsal-angular

MSAL - MsalGuard on Redirect URI - getting into redirect loop


I'm implementing msal in my angular application and I'm using msal-v1 library.

I have taken angular-7 sample from the documented samples and tried implementing the below code in my enterprise application.

I have added popup as false in app.module.ts

MsalModule.forRoot(
      {
        auth: {
          clientId: "app client id",
          authority:
            "https://login.microsoftonline.com/tenant.onmicrosoft.com/",
          validateAuthority: true,
          redirectUri: window.location.origin,
          postLogoutRedirectUri:
            window.location.origin,
          navigateToLoginRequestUrl: true,
        },
        cache: {
          cacheLocation: "localStorage",
          storeAuthStateInCookie: isIE, // set to true for IE 11
        },
      },
      {
        popUp: false,
        consentScopes: ["user.read", "openid", "profile"],
        unprotectedResources: ["https://www.microsoft.com/en-us/"],
        protectedResourceMap,
        extraQueryParameters: {},
      }
    )

and on app-routing.module.ts, I have added MsalGuard on the empty route as my application wont have any login button and the default landing page also needs authentication.

const routes: Routes = [
  {
    path: "",
    component: HomeComponent,
    canActivate: [MsalGuard],
  },
  {
    path: "profile",
    component: ProfileComponent,
    canActivate: [MsalGuard],
  },
];

@NgModule({
  imports: [RouterModule.forRoot(routes, { useHash: false })],
  exports: [RouterModule],
})
export class AppRoutingModule {}

By doing this, if I directly hit the domain URL(i.e. redirect URI) with out any route, I was able to authorize and get token properly in the localstorage, but if we clear local storage and then directly navigate to profile path, I was not able to get the token as it is entering a continuously redirect loop.

the application is redirecting to /#id_token=eyJ and then to /profile/#id_token=eyJ and so on.

please guide me on how to guard all routes in my angular application and not enter the redirect loop.

msal version - 1.4.4
msal-angular - 1.1.2

Solution

  • I have discussed the same issue in the github(msal-v1) forum and have found a alternate solution by setting a new route without the MsalGuard but to the same HomeComponent.

    const routes: Routes = [
      {
        path: '',
        component: HomeComponent,
        canActivate: [
          MsalGuard
        ]
      },
      {
        path: 'auth-redirect',
        component: HomeComponent
      },
      {
        path: 'profile',
        component: ProfileComponent,
        canActivate: [
          MsalGuard
        ]
      }
    ];
    

    full details are discussed here