MSAL angular inicializálása

@azure/msal-angular használata előtt regisztráljon egy alkalmazást a Microsoft Entra ID-ben, hogy megszerezze a(z) clientId-t.

Az MSAL modul belefoglalása és inicializálása az alkalmazásmodulba

Importáld az app.module.ts fájlba: MsalModule. Az MSAL modul inicializálásához adja át az alkalmazás ügyfélazonosítóját, amelyet az alkalmazásregisztrációból kap.

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

Az útvonalak védelme az alkalmazásban

Adjon hozzá hitelesítést az adott útvonalak biztonságossá tételéhez az alkalmazásban az útvonaldefiníció hozzáadásával canActivate: [MsalGuard] . Adja hozzá a szülő- vagy gyermekútvonalakhoz. Amikor egy felhasználó felkeresi ezeket az útvonalakat, a kódtár megkéri a felhasználót a hitelesítésre.

Tudjon meg többet a konfigurációról és a kapcsolódó megfontolásokról, beleértve a további interfészek használatát is, a MsalGuarddokumentációban.

Íme egy példa a következővel definiált útvonalra 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 { }

Tokenek lekérése webes API-hívásokhoz

@azure/msal-angular lehetővé teszi, hogy az alábbiak szerint HTTP-interceptort (MsalInterceptor) adjon hozzá a(z) app.module.ts elemhez. A MsalInterceptor lekéri a tokeneket, és hozzáadja azokat az API-hívásokban szereplő összes HTTP-kéréséhez a protectedResourceMap alapján. A konfigurációval és a használatkal kapcsolatos további részletekért tekintse meg az MsalInterceptor-dokumentumot .

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

MsalInterceptor A használata nem kötelező. Lehet, hogy inkább kifejezetten az acquireToken API-k használatával szeretné lekérni a tokeneket.

Vegye figyelembe, hogy az MsalInterceptor ön kényelme érdekében van megadva, és előfordulhat, hogy nem minden használati esetnek felel meg. Írjon saját interceptort, ha olyan speciális igényei vannak, amelyekre a MsalInterceptor nem nyújt megoldást.

Feliratkozás az eseményekre

Az MSAL olyan eseményrendszert biztosít, amely a hitelesítéshez és az MSAL-hoz kapcsolódó eseményeket bocsát ki. Az események használatához adja hozzá a MsalBroadcastService elemet az összetevő vagy szolgáltatás konstruktorába.

1. Az eseményekre való feliratkozás menete

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. Elérhető események

Az eseménydokumentációban@azure/msal-browser megtalálja az MSAL számára elérhető események listáját.

3. Leiratkozás

A leiratkozás fontos. Implementálja a(z) ngOnDestroy() elemet a komponensében a leiratkozáshoz.

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

Következő lépések

Készen áll a @azure/msal-angular használatára.