Search code examples
angularazure-ad-msalangular11msal-angular

How to pass clientId in different environment to AppModule


I use msal to do authentication. In my AppModule.ts (from the example)

    @NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    ProfileComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    MsalModule.forRoot( new PublicClientApplication({
      auth: {
        clientId: 'Enter_the_Application_Id_here', // This is your client ID
        authority: 'Enter_the_Cloud_Instance_Id_Here'/'Enter_the_Tenant_Info_Here', // This is your tenant ID
        redirectUri: 'Enter_the_Redirect_Uri_Here'// This is your redirect URI
      },
      cache: {
        cacheLocation: 'localStorage',
        storeAuthStateInCookie: isIE, // Set to true for Internet Explorer 11
      }
    }), null, null)
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

For the clientId, I don't want to hard code here. It is in the a config file. The question is that I have different environment such as dev/qa and prod etc. The clientId is different in each endpoint.

How to pass the value rather than hardcode to AppModule?


Solution

  • You could create environment.[stage].ts files for every stage under './src/environments/'.

    // environment.ts
    export const environment = {
      production: false,
      clientId: 'Enter_the_Application_Id_here',
      authority: 'Enter_the_Cloud_Instance_Id_Here',
      redirectUri: 'Enter_the_Redirect_Uri_Here'
    }
    
    // environment.qa.ts
    export const environment = {
      production: true,
      clientId: 'Enter_the_Application_Id_here',
      authority: 'Enter_the_Cloud_Instance_Id_Here',
      redirectUri: 'Enter_the_Redirect_Uri_Here'
    }
    

    When finished you should have N files for each stage. For example:

    1. environment.ts
    2. environment.qa.ts
    3. environment.prod.ts

    With some additional configuration of each [stage] inside angular.json you can easily do this:

    import { environment } from './../environments/environment';
    
    //inside app.module
       MsalModule.forRoot( new PublicClientApplication({
          auth: {
            clientId: environment.clientId,
            authority: environment.authority,
            redirectUri: environment.redirectUri
          },
    

    The addtional configuration inside angular.json adds a "fileReplacements" to replace environment.ts with envirnment.[stage].ts:

    "configurations": {
      "qa": {
        "fileReplacements": [
          {
            "replace": "src/environments/environment.ts",
            "with": "src/environments/environment.qa.ts"
          }
        ],
    

    Now you can run stage specific builds:

    ng build --configuration=qa
    

    The official angular documentation has a page about this topic: https://angular.io/guide/build