Integrating Microsoft Authentication into a Single Page Application using OAuth 2.0 - Code flow with PKCE
Integrating Microsoft Authentication into your Single Page Application (SPA) is relatively straightforward. Microsoft provides extensive documentation and tutorials on integrating it into your app. This article illustrates this process using an Angular application as an example.
Start by creating an application in Azure Active Directory. Go to Azure portal (Learn how to create an azure active directory application)
Install the required packages into your project using the following command:
1npm install @azure/msal-browser @azure/msal-angular
Proceed to configure the
MsalModule
in theapp.module.ts
:1imports: [ 2 MsalModule.forRoot(new PublicClientApplication({ 3 auth: { 4 clientId: '<ClientId>', 5 authority: '<AuthorityId>', 6 redirectUri: environment.ssoRedirectUrl 7 }, 8 cache: { 9 cacheLocation: 'localStorage', 10 storeAuthStateInCookie: isIE, 11 } 12 }), 13 { 14 interactionType: InteractionType.Redirect, 15 authRequest: { 16 scopes: ['user.read'] 17 } 18 }, 19 { 20 interactionType: InteractionType.Redirect, 21 protectedResourceMap: new Map([ 22 ['https://graph.microsoft.com', ['user.read','Directory.Read.All']] 23 ]) 24 }),
Integrate the
@azure/msal-angular/MsalBroadcastService
in yourapp.component.ts
:1this.broadcastService.inProgress$ 2 .pipe( 3 filter((status: InteractionStatus) => status === InteractionStatus.None), 4 takeUntil(this._destroying$) 5 ) 6 .subscribe(() => { 7 //login routine 8 this.isLoggedIn = this.authService.instance.getAllAccounts().length > 0; 9 this.profile$ = this.httpClient.get('https://graph.microsoft.com/v1.0/me'); 10 });
Integrate the
MsalInterceptor
, which automatically adds authentication to requests for protected resources:1providers: [ 2 { provide: HTTP_INTERCEPTORS, useClass: MsalInterceptor, multi: true }, 3],
Add
MsalGuard
to protect routes requiring Authentication:1@NgModule({ 2 imports: [RouterModule.forRoot([ 3 { path: '', component: EmployeeSalaryComponent, pathMatch: 'full', canActivate: [MsalGuard] }, 4 { path: 'details', component: SomeComponent, canActivate: [MsalGuard] }, 5 6 { path: '**', redirectTo: '' } 7 ], { 8 initialNavigation: 'enabledBlocking' 9 })], 10 exports: [RouterModule] 11})
Thanks to Microsoft's comprehensive documentation and examples, it took about 1 hour to successfully carry out the first login process within my application. To get more data from the currently logged-in user, you can explore the API at Microsoft Graph Explorer.