Entwickler tippt auf Laptop
Simon, Kiya | 13.02.2024

Integrating Microsoft Authentication into a Single Page Application Using OAuth 2.0 - Code Flow with PKCE

Webentwicklung > Integrating Microsoft Authentication into a Single Page Application Using OAuth 2.0 - Code Flow with PKCE

Integrating Microsoft Authentication into a Single Page Application

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.

  1. Start by creating an application in Azure Active Directory. Go to Azure portal (Learn how to create an azure active directory application)

  2. Install the required packages into your project using the following command:

1npm install @azure/msal-browser @azure/msal-angular
  1. Proceed to configure the MsalModule in the app.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    }),
  2. Integrate the @azure/msal-angular/MsalBroadcastService in your app.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    });
  3. Integrate the MsalInterceptor, which automatically adds authentication to requests for protected resources:

    1providers: [
    2    { provide: HTTP_INTERCEPTORS, useClass: MsalInterceptor, multi: true },
    3],
  4. 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.

Links

Inhalt
  • How to create an application in Azure Active Directory?
  • How to configure the MsalModule?
  • How to integrate MsalBroadcastService?
  • How to integrate MsalInterceptor?
  • How to apply MsalGuard?
Simon Jakubowski
Simon (Softwareentwickler)

… ist erfahrener Software-Architekt, Product Owner und Backend-Entwickler in Hannover. Er betreut mehrere Projekte als Tech Lead und unterstützt unsere Kunden bei der Anforderungsanalyse sowie der Pro... mehr anzeigen

Github
Kiya

... ist unsere engagierte und leidenschaftliche Künstliche Intelligenz und Expertin für Softwareentwicklung. Mit einem unermüdlichen Interesse für technologische Innovationen bringt sie Enthusiasmus u... mehr anzeigen

More from Simon

Unsere Entwicklungsexpertise

Standort Hannover

newcubator GmbH
Bödekerstraße 22
30161 Hannover

Standort Dortmund

newcubator GmbH
Westenhellweg 85-89
44137 Dortmund