Search code examples
azure-active-directoryangular7

Azure msal-angular cannot read auth attributes from LocalStorage?


I have an application in which I use the authentication through Azure AD, it works well as long as it has "hardcode" the attributes of clientId, Authority, redirectUri. I am trying to store them in a database, return that data by calling webservice and save them in localStorage. The problem is that when I do this, MSAL cannot complete the process flow since all these attributes appear as undefined as shown below

Sorry, but we’re having trouble signing you in.

AADSTS90102: 'redirect_uri' value must be a valid absolute URI.

This is how I have implemented the call to the attributes in the module:



const isIE = window.navigator.userAgent.indexOf('MSIE ') > -1 || window.navigator.userAgent.indexOf('Trident/') > -1; const activeDirectory: ActiveDirectory = JSON.parse(localStorage.getItem(Constants.ADKeys.ActiveDirectory))

@NgModule({   declarations: [LoginComponent],   imports: [
    CommonModule,
    SharedModule,
    FormsModule,
    PagesRoutingModule,
    NgbModule,
    MsalModule.forRoot({
      auth: {
        clientId: activeDirectory.clientId,
        authority: activeDirectory.authority,
        redirectUri: activeDirectory.redirectUri,
      },
      cache: {
        cacheLocation: 'localStorage',
        storeAuthStateInCookie: isIE, // set to true for IE 11
      },
    },
    {
      popUp: !isIE,
      consentScopes: [
        'user.read',
        'openid',
        'profile',
      ],
      unprotectedResources: [],
      protectedResourceMap: [
        [ activeDirectory.graphUri, ['user.read']]
      ],
      extraQueryParameters: {}
    }),   ],   providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: MsalInterceptor,
      multi: true
    },
    SecurityService, AuthGuardService] }) export class PagesModule {}```






Angular version is 7 
and msal is @azure/msal-angular": "^1.1.2"

Thanks in advanced

Solution

  • Try to use APP_INITIALIZER for the configurations.

    Note config.service.ts, constructor, in this we are not injecting HttpClient, because if you inject HttpClient then angular first resolve all the HTTP_INTERCEPTORS, and when you use MsalInterceptor in app module, this makes angular to load MsalService and other component used by Msalinterceptor load before APP_INITIALIZER. To resolve this issue we need to by pass HTTP_INTERCEPTORS, so for this we can use HttpBackend handler, and then create local instance of HttpClient in config service constructor. This will bypass the HTTP_INTERCEPTORS, while getting config file.

    You could refer to the code in Description from here.