Reputation: 536
Is it possible to dynamically include or exclude an interceptor?
For example, I would like to enable Azure AD based SSO in my application using microsoft's @azure/msal-angular package https://www.npmjs.com/package/@azure/msal-angular that provides an interceptor. However, I intend my application to run in two modes - one with SSO based on msal package provided interceptor and one without (i.e. route authentication to some other backend server instead of azure AD). Therefore, i want to include msal interceptor if SSO mode is selected and i wish to to exclude this interceptor if SSO mode is not selected at run time by a user. How do I implement this dynamically based on what user chooses on login screen? Further details below:
Below is what microsoft provides as a sample application that uses their package for authentication https://github.com/AzureAD/microsoft-authentication-library-for-js/tree/dev/samples/msal-angular-v2-samples/angular11-sample-app
app.module.ts of sample application has following way of including msal interceptor (snippet included). This always routes http to Azure AD for authenticaion. How can I dynamically remove this if my user doesn't want this type of authentication?
@NgModule({
declarations: [
AppComponent,
HomeComponent,
ProfileComponent,
DetailComponent,
LogoutComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
AppRoutingModule,
MatButtonModule,
MatToolbarModule,
MatListModule,
MatMenuModule,
HttpClientModule,
MsalModule
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: MsalInterceptor,
multi: true
},
{
provide: MSAL_INSTANCE,
useFactory: MSALInstanceFactory
},
{
provide: MSAL_GUARD_CONFIG,
useFactory: MSALGuardConfigFactory
},
{
provide: MSAL_INTERCEPTOR_CONFIG,
useFactory: MSALInterceptorConfigFactory
},
MsalService,
MsalGuard,
MsalBroadcastService
],
bootstrap: [AppComponent, MsalRedirectComponent]
})
export class AppModule { }
Upvotes: 2
Views: 1015
Reputation: 147
You can add an environment variable flag like sso
and based on its value add msal providers.
in environment.dev.ts
export const ENVIRONMENT = {
..........,
sso: false,
..........,
};
in environment.prod.ts
export const ENVIRONMENT = {
..........,
sso: true,
..........,
};
in app.module.ts
const MSAL_PROVIDERS = [
{ provide: HTTP_INTERCEPTORS, useClass: MsalInterceptor, multi: true },
{ provide: MSAL_INSTANCE, useFactory: MSALInstanceFactory },
{ provide: MSAL_GUARD_CONFIG, useFactory: MSALGuardConfigFactory },
{ provide: MSAL_INTERCEPTOR_CONFIG, useFactory: MSALInterceptorConfigFactory },
MsalService,
MsalGuard,
MsalBroadcastService
]
@NgModule({
declarations: [ ....... ],
imports: [ ....... ],
providers: [
............,
ENVIRONMENT.sso ? MSAL_PROVIDERS : []
],
});
Hope it works.
Upvotes: 2