Angular APP_INITIALIZER in module not working properly
Asked Answered
A

2

6

I have auth module which imports and sets msal configuration before app is initializer. I'm using APP_INITIALIZER to block the init of the app and get configuration for MSAL-ANGULAR. The issue is only with Firefox. The app is working perfectly fine on Chrome, Egde, Safari but not on Firefox. On every other browser different than Firefox APP_INITIALIZER is blocking startup until config.json is loaded. What I noticed is MSALInstanceFactory is called before initializerFactory function.

Code that I'm using in auth.module

export function initializerFactory(env: ConfigService, configUrl: string): any {
// APP_INITIALIZER, angular doesnt starts application untill it completes loading config.json
  const promise = env.init(configUrl).then(val => {});
  return () => promise;
}

export function loggerCallback(logLevel: LogLevel, message: string): void {
   console.log(message);
}

export function MSALInstanceFactory(configService: ConfigService, constant: SecurityConstants): IPublicClientApplication {
   return new PublicClientApplication({
      auth: {
         clientId: configService.getSettings('clientId'),
         redirectUri: configService.getSettings('redirectUri'),
         authority: configService.getSettings('authority'),
      },
      cache: {
         cacheLocation: BrowserCacheLocation.LocalStorage,
         storeAuthStateInCookie: isIE,
      },
      system: {
         loggerOptions: {
            loggerCallback,
            logLevel: LogLevel.Info,
            piiLoggingEnabled: false,
         },
      },
   });
}

export function MSALInterceptorConfigFactory(configService: ConfigService, constant: SecurityConstants): MsalInterceptorConfiguration {
   const protectedResourceMap = new Map<string, Array<string>>();
   protectedResourceMap.set('/*/', [configService.getSettings('scope')]);
   return {
      interactionType: InteractionType.Redirect,
      protectedResourceMap,
   };
}

export function MSALGuardConfigFactory(configService: ConfigService, constant: SecurityConstants): MsalGuardConfiguration {
   return {
      interactionType: InteractionType.Redirect,
      authRequest: {
         scopes: [configService.getSettings('scope')],
      },
   };
}

@NgModule({
   imports: [MsalModule]
})
export class AuthModule {
   static forRoot(configFile: string) {
      return {
         ngModule: AuthModule,
         providers: [
            ConfigService,
            MsalService,
            { provide: AUTH_CONFIG_URL_TOKEN, useValue: configFile },
            {
               provide: APP_INITIALIZER,
               useFactory: initializerFactory,
               deps: [ConfigService, AUTH_CONFIG_URL_TOKEN, SecurityConstants],
               multi: true,
            },
            {
               provide: HTTP_INTERCEPTORS,
               useClass: MsalInterceptor,
               multi: true,
            },
            {
               provide: MSAL_INSTANCE,
               useFactory: MSALInstanceFactory, // this is initiated before APP_INITIALIZER 
               deps: [ConfigService, SecurityConstants],
            },
            {
               provide: MSAL_GUARD_CONFIG,
               useFactory: MSALGuardConfigFactory,
               deps: [ConfigService, SecurityConstants],
            },
            {
               provide: MSAL_INTERCEPTOR_CONFIG,
               useFactory: MSALInterceptorConfigFactory,
               deps: [ConfigService, SecurityConstants],
            },
            MsalGuard,
            MsalBroadcastService,
         ],
      };
   }
}

Code in ConfigService

   @Injectable({
       providedIn: 'root',
    })
    export class ConfigService {
       config: any;
       private http: HttpClient;
    
       constructor(private readonly httpHandler: HttpBackend) {
          this.http = new HttpClient(httpHandler);
       }
    
       init(endpoint: string): Promise<boolean> {
          let promise = new Promise<boolean>((resolve, reject) => {
             this.http
                .get<ConfigResponse>(endpoint)
                .pipe(map((res) => res))
                .subscribe(
                   (value) => {
                         this.config = value;
                   },
                   (error) => {
                      reject(false);
                   },
                   () => {
                      resolve(true);
                   }
                );
          });
             return promise;
       }
    
       getSettings(key?: string | Array<string>): any {
          if (!key || (Array.isArray(key) && !key[0])) {
             return this.config;
          }
    
          if (!Array.isArray(key)) {
             key = key.split('.');
          }
    
          let result = key.reduce((acc: any, current: string) => acc && acc[current], this.config);
    
          return result;
       }
    }

Code in app.module

@NgModule({
   declarations: [AppComponent],
   imports: [
      AuthModule.forRoot('assets/config.json'),
      CommonModule,
      BrowserModule,
      BrowserAnimationsModule,
      HttpClientModule,
      RouterModule
   ],
   bootstrap: [AppComponent, MsalRedirectComponent],
})
export class AppModule {}
Allantois answered 27/5, 2021 at 14:34 Comment(0)
A
3

What I found is APP_INITIALIZER doesn't guarantee that your configuration service completes first. This issue also is reported here: https://github.com/angular/angular/issues/23279 which sadly is still not resolved. Initially MSAL_Instance is loaded before that and in order to fix that issue I've changed the main.ts bootstrap module.

    // main.ts
function bootstrapFailed(val) {
    document.getElementById('bootstrap-fail').style.display = 'block';
    console.error('bootstrap-fail', val);
}

fetch('config.json')
    .then(response => response.json())
    .then(config => {
        if (!config || !config['isConfig']) {
            bootstrapFailed(config);
            return;
        }

   // Store the response somewhere that your ConfigService can read it.
   window['tempConfigStorage'] = config;

    platformBrowserDynamic()
            .bootstrapModule(AppModule)
            .catch(bootstrapFailed);
    })
    .catch(bootstrapFailed);
Allantois answered 28/5, 2021 at 12:27 Comment(0)
I
1

I also had problems with APP_INITIALIZER.

I have found that if I replace this line of app-routing.module (that was mentioned in the documentation)

initialNavigation: !isIframe ? 'enabled' : 'disabled'

with this

initialNavigation: !isIframe ? 'enabledNonBlocking' : 'disabled'

the problem is resolved!

You can also use msal's BrowserUtils instead of isIframe variable.

initialNavigation: !BrowserUtils.isInIframe() && !BrowserUtils.isInPopup() ? 'enabledNonBlocking' : 'disabled'
Ingar answered 2/3, 2022 at 13:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.