21.9.2022 |

Integrate Microsoft Authentication into a Single Page Application using OAuth 2.0 - Code flow with PKCE

It's rather simple to integrate Microsoft Authentication into your Single Page Application. Microsoft provides really good documentation and Tutorials about how to integrate it into your App. Here's an example on how to integrate it into an Angular Application.

  1. Create an Application in Azure Active Directory. Go to https://portal.azure.com/ (see: how to create an azure active directory application)
  2. npm install @azure/msal-browser @azure/msal-angular in your project
  3. Configure the MsalModule in the app.module.ts
imports: [
  MsalModule.forRoot(new PublicClientApplication({
      auth: {
        clientId: '<ClientId>',
        authority: '<AuthorityId>',
        redirectUri: environment.ssoRedirectUrl
      },
      cache: {
        cacheLocation: 'localStorage',
        storeAuthStateInCookie: isIE, // Set to true for Internet Explorer 11
      }
    }),
    {
      interactionType: InteractionType.Redirect,
      authRequest: {
        scopes: ['user.read']
      }
    },
    {
      interactionType: InteractionType.Redirect, // MSAL Interceptor Configuration
      protectedResourceMap: new Map([
        ['https://graph.microsoft.com', [
          'user.read',
          'Directory.Read.All' //Directory.Read.All: only required when reading Active Directory groups
        ]]
      ])
    }),
  1. Integrate the @azure/msal-angular/MsalBroadcastService in your app.component.ts
  this.broadcastService.inProgress$
    .pipe(
      filter((status: InteractionStatus) => status === InteractionStatus.None),
      takeUntil(this._destroying$)
    )
    .subscribe(() => {
      //do login routine
      this.isLoggedIn = this.authService.instance.getAllAccounts().length > 0;
      this.profile$ = this.httpClient.get('https://graph.microsoft.com/v1.0/me');
    });
  1. Integrate the MsalInterceptor which automatically adds authentication to requests for protected resources
providers: [
  { provide: HTTP_INTERCEPTORS, useClass: MsalInterceptor, multi: true },
],
  1. Add MsalGuard to protect routes requiring Authentication:
@NgModule({
  imports: [RouterModule.forRoot([
    { path: '', component: EmployeeSalaryComponent, pathMatch: 'full', canActivate: [MsalGuard] },
    { path: 'details', component: SomeComponent, canActivate: [MsalGuard] },

    { path: '**', redirectTo: '' }
  ], {
    initialNavigation: 'enabledBlocking'
  })],
  exports: [RouterModule]
})

It was rather simple to integrate Microsoft due to the really good documentation and examples provided by Microsoft. It took me about 1 hour from the start to the first successful login within my application. To get more information from the currently logged in user, you can explore the API at https://developer.microsoft.com/en-us/graph/graph-explorer

Links:

Simon
Zur Übersicht

Mehr vom DevSquad...

Tim Tilch

Snippets Lab

Sophia Brandt

Angular 14 Features