MSAL Angular initialiseren

Voordat u @azure/msal-angular gebruikt, moet u een toepassing registreren in Microsoft Entra ID om de clientId op te halen.

De MSAL-module opnemen en initialiseren in uw app-module

Importeer MsalModule in app.module.ts. Als u de MSAL-module wilt initialiseren, geeft u de clientId van uw toepassing door, die u krijgt van de registratie van de toepassing.

import { NgModule } from '@angular/core';
import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import { MsalModule, MsalService, MsalGuard, MsalInterceptor, MsalBroadcastService, MsalRedirectComponent } from "@azure/msal-angular";
import { PublicClientApplication, InteractionType, BrowserCacheLocation } from "@azure/msal-browser";

@NgModule({
    imports: [
        MsalModule.forRoot( new PublicClientApplication({ // MSAL Configuration
            auth: {
                clientId: "Your client ID",
                authority: "Your authority",
                redirectUri: "Your redirect Uri",
            },
            cache: {
                cacheLocation : BrowserCacheLocation.LocalStorage,
            },
            system: {
                loggerOptions: {
                    loggerCallback: () => {},
                    piiLoggingEnabled: false
                }
            }
        }), {
            interactionType: InteractionType.Redirect, // MSAL Guard Configuration
        }, {
            interactionType: InteractionType.Redirect, // MSAL Interceptor Configuration
        })
    ],
    providers: [
        {
            provide: HTTP_INTERCEPTORS,
            useClass: MsalInterceptor,
            multi: true
        },
        MsalService,
        MsalGuard,
        MsalBroadcastService
    ],
    bootstrap: [AppComponent, MsalRedirectComponent]
})
export class AppModule {}

De routes in uw toepassing beveiligen

Voeg verificatie toe om specifieke routes in uw toepassing te beveiligen door deze toe te voegen aan canActivate: [MsalGuard] uw routedefinitie. Voeg het toe aan bovenliggende of onderliggende routes. Wanneer een gebruiker deze routes bezoekt, vraagt de bibliotheek de gebruiker om zich te verifiëren.

Meer informatie vindt u in ons MsalGuard document over configuratie en overwegingen, waaronder het gebruik van extra interfaces.

Hier is een voorbeeld van een route die is gedefinieerd met de MsalGuard:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { ProfileComponent } from './profile/profile.component';
import { MsalGuard } from '@azure/msal-angular';

const routes: Routes = [
    {
        path: 'profile',
        component: ProfileComponent,
        canActivate: [MsalGuard]
    },
    {
        path: '',
        component: HomeComponent
    },
];

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class AppRoutingModule { }

Tokens ophalen voor web-API-aanroepen

@azure/msal-angular stelt u in staat om als volgt een Http-interceptor (MsalInterceptor) toe te voegen in uw app.module.ts. De MsalInterceptor haalt tokens op en voegt deze toe aan al uw HTTP-verzoeken bij API-aanroepen op basis van de protectedResourceMap. Zie ons MsalInterceptor-document voor meer informatie over configuratie en gebruik.

import { NgModule } from '@angular/core';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { AppComponent } from './app.component';
import { MsalModule, MsalService, MsalGuard, MsalInterceptor, MsalBroadcastService, MsalRedirectComponent } from "@azure/msal-angular";
import { PublicClientApplication, InteractionType, BrowserCacheLocation } from "@azure/msal-browser";

@NgModule({
    imports: [
        MsalModule.forRoot( new PublicClientApplication({ // MSAL Configuration
            auth: {
                clientId: "Your client ID",
                authority: "Your authority",
                redirectUri: "Your redirect Uri",
            },
            cache: {
                cacheLocation : BrowserCacheLocation.LocalStorage,
            },
            system: {
                loggerOptions: {
                    loggerCallback: () => {},
                    piiLoggingEnabled: false
                }
            }
        }), {
            interactionType: InteractionType.Redirect, // MSAL Guard Configuration
        }, {
            interactionType: InteractionType.Redirect, // MSAL Interceptor Configuration
            protectedResourceMap: new Map([
                ['https://graph.microsoft.com/v1.0/me', ['user.read']],
                ['https://api.myapplication.com/users/*', ['customscope.read']],
                ['http://localhost:4200/about/', null] 
            ])
        })
    ],
    providers: [
        {
            provide: HTTP_INTERCEPTORS,
            useClass: MsalInterceptor,
            multi: true
        },
        MsalService,
        MsalGuard,
        MsalBroadcastService
    ],
    bootstrap: [AppComponent, MsalRedirectComponent]
})
export class AppModule {}

Het gebruik van de MsalInterceptor optie is optioneel. Mogelijk wilt u in plaats daarvan expliciet tokens ophalen met behulp van de acquireToken-API's.

Houd er rekening mee dat de MsalInterceptor voor uw gemak wordt aangeboden en mogelijk niet voor alle toepassingen geschikt is. Schrijf uw eigen interceptor als u specifieke vereisten hebt die niet worden afgedekt door de MsalInterceptor.

Abonneren op gebeurtenissen

MSAL biedt een gebeurtenissysteem waarmee gebeurtenissen met betrekking tot verificatie en MSAL worden verzonden. Voeg MsalBroadcastService toe aan de constructor in uw component of service om gebeurtenissen te gebruiken.

1. Abonneren op gebeurtenissen

import { EventMessage, EventType } from '@azure/msal-browser';
import { filter } from 'rxjs/operators';

this.msalBroadcastService.msalSubject$
    .pipe(
        filter((msg: EventMessage) => msg.eventType === EventType.LOGIN_SUCCESS)
    )
    .subscribe((result) => {
        // do something here
    });

2. Beschikbare gebeurtenissen

Zoek in de @azure/msal-browser gebeurtenisdocumentatie de lijst met gebeurtenissen die beschikbaar zijn voor MSAL.

3. Afmelden

Afmelden is belangrijk. Implementeer ngOnDestroy() in uw onderdeel om u af te melden.

import { EventMessage, EventType } from '@azure/msal-browser';
import { filter, Subject, takeUntil } from 'rxjs';

private readonly _destroying$ = new Subject<void>();

this.msalBroadcastService.msalSubject$
    .pipe(
        filter((msg: EventMessage) => msg.eventType === EventType.LOGIN_SUCCESS),
        takeUntil(this._destroying$)
    )
    .subscribe((result) => {
        this.checkAccount();
    });

ngOnDestroy(): void {
    this._destroying$.next(null);
    this._destroying$.complete();
}

Volgende stappen 

U bent klaar om @azure/msal-angular te gebruiken.