Initiera MSAL-angular

Innan du använder @azure/msal-angularregistrerar du ett program i Microsoft Entra ID för att hämta clientId.

Inkludera och initiera MSAL-modulen i din appmodul

Importera MsalModule till app.module.ts. Om du vill initiera MSAL-modulen skickar du clientId för ditt program, som du får från programregistreringen.

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 {}

Skydda vägarna i ditt program

Lägg till autentisering för att skydda specifika vägar i ditt program genom att lägga canActivate: [MsalGuard] till i routningsdefinitionen. Lägg till den i överordnade eller underordnade vägar. När en användare besöker dessa vägar uppmanas användaren att autentisera i biblioteket.

Läs mer i vårt MsalGuard dokument om konfiguration och överväganden, inklusive användning av ytterligare gränssnitt.

Här är ett exempel på en väg som definierats med 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 { }

Hämta token för webb-API-anrop

@azure/msal-angular gör att du kan lägga till en Http-interceptor (MsalInterceptor) på app.module.ts följande sätt. MsalInterceptor hämtar alla token och lägger till dem i alla dina HTTP-begäranden vid API-anrop baserat på protectedResourceMap. Mer information om konfiguration och användning finns i msalInterceptor-dokumentet .

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 {}

Det är valfritt att MsalInterceptor använda. Du kanske uttryckligen vill hämta token med hjälp av acquireToken-API:erna i stället.

Observera att MsalInterceptor tillhandahålls för enkelhets skull och kanske inte passar alla användningsområden. Skriv en egen interceptor om du har specifika behov som inte tillgodoses av MsalInterceptor.

Prenumerera på händelser

MSAL tillhandahåller ett händelsesystem som genererar händelser relaterade till autentisering och MSAL. Om du vill använda händelser lägger du till MsalBroadcastService i konstruktorn i din komponent eller tjänst.

1. Så här prenumererar du på händelser

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. Tillgängliga händelser

Hitta listan över händelser som är tillgängliga för MSAL i händelsedokumentationen@azure/msal-browser.

3. Avprenumerera

Det är viktigt att avbryta prenumerationen. Implementera ngOnDestroy() i komponenten för att avbryta prenumerationen.

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();
}

Nästa steg

Du är redo att använda @azure/msal-angularoffentliga API:er.