Search code examples
angularconfigurationpost-buildmsal-angular

Dynamic configuration of MSAL 2 in Angular


For my Angular (v12) application, I use MSAL for Authentication and I'm facing an issue on configuration.

In configuration, I have tenantId and app Id to initialize MSAL.

I cannot use the standard Angular configuration switching with environment.ts since it cannot be changed in a post build step.

Instead, I try to load a json file and call at app startup using APP_INITIALIZER callback as it is explained in this post : How to initialize msal configurations using APP_INITIALIZER

I've modified it a bit since MsalAngularConfiguration doesn't exist anymore in MSAL v2.

But it's not working, a call to MSALInstanceFactory is done before ConfigService.init is called (by AppComponent since it depends from MsalGuardConfiguration).

I've tried also to pass ConfigService in msalConfigFactory function, but the parameter is undefined.

I've also tried to import in code as json, but it doesn't work since I got the values when it was built.

Any idea?


Solution

  • It seems that i've double used my AppConfigService in providers. I've done the same using a local factory, and it works:

    export function EnvConfigurationFactory(httpBackend: HttpBackend) {
    
      return () => {
        let http = new HttpClient(httpBackend);
        return http.get('assets/configuration/environment.json')
                .toPromise()
                .then((resp) => {
                  for (var key in resp) {
                    environment[key] = resp[key];
                  }
                })
      }
    } 
    

    I'm using HttpBackend instead of HttpClient since an HTTP_INTERCEPTORS is configured and use the settings I try to set. And I set directly the values of environment object with environment.json file.