How to Configure MSAL Authentication in a Angular 16
Prerequisites
By following these prerequisites, you can ensure a smooth and successful installation of the Microsoft Authentication Library.
Create a new project
You can use an existing Angular app project or create a new one. Before starting an Angular project, you should have the following prerequisites installed on your system
- Node.js
- npm (Node Package Manager)
- Angular CLI
Once you have installed these prerequisites, you are ready to create your first Angular application.
Register an Application in Azure AD
Prior to utilizing Microsoft Authentication Library(MSAL), make sure to register an application in Azure AD to obtain your clientId.
Sign in to the Microsoft Entra admin center.
Check How to Register an application in Microsoft Entra ID
Install the dependencies
Microsoft Authentication Library (MSAL Browser "@azure/msal-browser" and MSAL Angular "@azure/msal-angular" ) for Angular allows Angular web applications to authenticate users using Azure AD work and School Accounts (AAD) and Microsoft personal accounts (MSA) through the Azure AD B2C service. It also facilitates application in obtaining tokens for accessing Microsoft Cloud services.
The @azure/msal-browser and @azure/msal-angular package are available on Node Package Manager.
npm install @azure/msal-browser @azure/msal-angular@latest
Configure Application settings
In your src/environments folder, environment.ts file add the following code. Then update the keys with the corresponding values
- clientId - The application's identifier, also known as the client identifier.
- authority -This consists of two components Instance and Tenant ID (https://login.microsoftonline.com/tenant ID)
- redirectUri - The Angular application route name to which the authorization server redirects the user after the application has been successfully authorized and provided with an access token. like http://localhost:4200
- postLogoutRedirectUri -The route name to which the authorization server redirects the user after the application logout
You will get all this information from Microsoft Entra ID
export const environment = {
API: 'https://coretrade.azurewebsites.net/api',
msalConfig: {
auth: {
clientId: 'enter-clientId',
// clientId: '00000-0000-0000-00000-000000000',
authority: 'enter-authority'
// authority : https://login.microsoftonline.com/000000-00000-0000-0000000-00000000
}
},
apiConfig: {
scopes: ['user.read'],
uri: 'https://graph.microsoft.com/v1.0/me'
}
};
Configure the MsalGuard
The MsalGuard class is use to secure routes, ensuring authentication is necessary before accessing protected routes.
The subsequent steps include incorporating the MsalGuard into the application.
- Create new function MSALGuardConfigFactory in src/app/function.ts.
- import the MsalGuard class from @azure/msal-angular add as a provider in your application in src/app/app.module.ts.
- Add the MsalGuard to app routing module "app-routing.module.ts".
export function MSALGuardConfigFactory(): MsalGuardConfiguration {
return {
interactionType: InteractionType.Redirect,
authRequest: {
scopes: [...environment.apiConfig.scopes]
},
loginFailedRoute: '/auth/login'
};
}
providers: [{
provide: MSAL_GUARD_CONFIG,
useFactory: MSALGuardConfigFactory
}]
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { MsalGuard } from '@azure/msal-angular';
import { MainshellComponent } from './shared/mainshell/mainshell.component';
import { AuthshellComponent } from './shared/authshell/authshell.component';
const routes: Routes = [
{
path: '', component: MainshellComponent,
canActivate:[MsalGuard],
children: [{
path: '', loadChildren: () => import('./core/core.module').then((m => m.CoreModule))
}]
},
{
path: 'auth', component: AuthshellComponent,
children: [{
path: '', loadChildren: () => import('./auth/auth.module').then((m => m.AuthModule))
}]
}
];
@NgModule({
imports: [RouterModule.forRoot(routes, { useHash: true })],
exports: [RouterModule]
})
export class AppRoutingModule { }
Configure the MsalInterceptor
The @azure/msal-angular package provides an Interceptor class that automatically obtains tokens for outbound requests made through the Angular HTTP client to recognized secured resources.
The subsequent steps include incorporating the MsalGuard into the application.
- Create new function MSALGuardConfigFactory in src/app/function.ts.
- Add the MsalGuard class as a provider in your application in src/app/app.module.ts,
export function MSALInterceptorConfigFactory(): MsalInterceptorConfiguration {
const protectedResourceMap = new Map<string, Array<string>>();
protectedResourceMap.set(environment.apiConfig.uri, environment.apiConfig.scopes);
return {
interactionType: InteractionType.Redirect,
protectedResourceMap
};
}
providers: [{
provide: MSAL_INTERCEPTOR_CONFIG,
useFactory: MSALInterceptorConfigFactory
}]
Configure the bootstrap component
bootstrap: [AppComponent, MsalRedirectComponent]
<body class="mat-typography">
<app-root></app-root>
<app-redirect></app-redirect>
</body>
Configure the app module
In the src/app folder, app.module.ts file code should look similar to the following sample.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { Interceptor } from './service/HttpInterceptor ';
import { SideNavigationComponent } from './shared/side-navigation/side-navigation.component';
import { TopNavigationComponent } from './shared/top-navigation/top-navigation.component';
import { IPublicClientApplication, PublicClientApplication, InteractionType, BrowserCacheLocation, LogLevel } from '@azure/msal-browser';
import { MsalGuard, MsalInterceptor, MsalBroadcastService, MsalInterceptorConfiguration, MsalModule, MsalService, MSAL_GUARD_CONFIG, MSAL_INSTANCE, MSAL_INTERCEPTOR_CONFIG, MsalGuardConfiguration, MsalRedirectComponent } from '@azure/msal-angular';
import { LoginComponent } from './auth/login/login.component';
import { environment } from 'src/environments/environment';
import { MainshellComponent } from './shared/mainshell/mainshell.component';
import { AuthshellComponent } from './shared/authshell/authshell.component';
import { RouterModule } from '@angular/router';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { AppRoutingModule } from './app-routing.module';
export function loggerCallback(logLevel: LogLevel, message: string) {
console.log(message);
}
@NgModule({
declarations: [
AppComponent,
SideNavigationComponent,
TopNavigationComponent,
LoginComponent,
MainshellComponent,
AuthshellComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
RouterModule,
MatProgressBarModule,
MsalModule,
AppRoutingModule,
],
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: Interceptor, multi: true },
{
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 { }
export function MSALInstanceFactory(): IPublicClientApplication {
return new PublicClientApplication({
auth: {
clientId: environment.msalConfig.auth.clientId,
authority: environment.msalConfig.auth.authority,
redirectUri: '/',
postLogoutRedirectUri: '/auth/login'
},
cache: {
cacheLocation: BrowserCacheLocation.LocalStorage
},
system: {
allowNativeBroker: false, // Disables WAM Broker
}
});
}
Conclusion
Thank you for reading this article. Hopefully now you know How to Configure MSAL Authentication in a Angular 16.