Självstudie: Lägga till inloggning och utloggning till ett Angular SPA för en extern klientorganisation
Den här självstudien är den sista delen i en serie som visar hur du skapar ett Angular-ensidesprogram (SPA) och förbereder det för autentisering med hjälp av administrationscentret för Microsoft Entra. I del 3 i den här serien har du lagt till autentiseringsflöden i ditt angular-ensidesprogram och konfigurerat flödena så att de fungerar med din externa klientorganisation. I den här artikeln får du lära dig hur du lägger till inloggnings- och utloggningsfunktioner i programmet. Slutligen testar du programmet.
I den här självstudien;
- Lägg till inloggnings- och utloggningsfunktioner i din app.
- Testa programmet
Förutsättningar
- Självstudie: Förbered din externa klientorganisation för att autentisera användare i ett Angular SPA.
Logga in och logga ut användare
Öppna src/app/app.component.ts och ersätt koden med följande för att logga in en användare med hjälp av en punkt av närvaro (POP)-up. Den här koden använder MSAL Angular-biblioteket för att logga in en användare.
import { Component, OnInit, Inject, OnDestroy } from '@angular/core'; import { MsalService, MsalBroadcastService, MSAL_GUARD_CONFIG, MsalGuardConfiguration, } from '@azure/msal-angular'; import { AuthenticationResult, InteractionStatus, InteractionType, PopupRequest, RedirectRequest, EventMessage, EventType } from '@azure/msal-browser'; import { Subject } from 'rxjs'; import { filter, takeUntil } from 'rxjs/operators'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent implements OnInit, OnDestroy { title = 'Microsoft identity platform'; loginDisplay = false; isIframe = false; private readonly _destroying$ = new Subject<void>(); constructor( @Inject(MSAL_GUARD_CONFIG) private msalGuardConfig: MsalGuardConfiguration, private authService: MsalService, private msalBroadcastService: MsalBroadcastService, ) { } ngOnInit(): void { this.isIframe = window !== window.parent && !window.opener; this.setLoginDisplay(); this.authService.instance.enableAccountStorageEvents(); // Optional - This will enable ACCOUNT_ADDED and ACCOUNT_REMOVED events emitted when a user logs in or out of another tab or window /** * You can subscribe to MSAL events as shown below. For more info, * visit: https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-angular/docs/v2-docs/events.md */ this.msalBroadcastService.inProgress$ .pipe( filter( (status: InteractionStatus) => status === InteractionStatus.None ), takeUntil(this._destroying$) ) .subscribe(() => { this.setLoginDisplay(); this.checkAndSetActiveAccount(); }); this.msalBroadcastService.msalSubject$ .pipe( filter( (msg: EventMessage) => msg.eventType === EventType.LOGOUT_SUCCESS ), takeUntil(this._destroying$) ) .subscribe((result: EventMessage) => { this.setLoginDisplay(); this.checkAndSetActiveAccount(); }); this.msalBroadcastService.msalSubject$ .pipe( filter( (msg: EventMessage) => msg.eventType === EventType.LOGIN_SUCCESS ), takeUntil(this._destroying$) ) .subscribe((result: EventMessage) => { const payload = result.payload as AuthenticationResult; this.authService.instance.setActiveAccount(payload.account); }); } setLoginDisplay() { this.loginDisplay = this.authService.instance.getAllAccounts().length > 0; } checkAndSetActiveAccount() { /** * If no active account set but there are accounts signed in, sets first account to active account * To use active account set here, subscribe to inProgress$ first in your component * Note: Basic usage demonstrated. Your app may require more complicated account selection logic */ let activeAccount = this.authService.instance.getActiveAccount(); if (!activeAccount && this.authService.instance.getAllAccounts().length > 0) { let accounts = this.authService.instance.getAllAccounts(); // add your code for handling multiple accounts here this.authService.instance.setActiveAccount(accounts[0]); } } login() { if (this.msalGuardConfig.interactionType === InteractionType.Popup) { if (this.msalGuardConfig.authRequest) { this.authService.loginPopup({ ...this.msalGuardConfig.authRequest, } as PopupRequest) .subscribe((response: AuthenticationResult) => { this.authService.instance.setActiveAccount(response.account); }); } else { this.authService.loginPopup() .subscribe((response: AuthenticationResult) => { this.authService.instance.setActiveAccount(response.account); }); } } else { if (this.msalGuardConfig.authRequest) { this.authService.loginRedirect({ ...this.msalGuardConfig.authRequest, } as RedirectRequest); } else { this.authService.loginRedirect(); } } } logout() { if (this.msalGuardConfig.interactionType === InteractionType.Popup) { this.authService.logoutPopup({ account: this.authService.instance.getActiveAccount(), }); } else { this.authService.logoutRedirect({ account: this.authService.instance.getActiveAccount(), }); } } // unsubscribe to events when component is destroyed ngOnDestroy(): void { this._destroying$.next(undefined); this._destroying$.complete(); } }
Testa ditt program
Starta webbservern genom att köra följande kommandon i en kommandotolk från programmappen:
npm install npm start
I webbläsaren anger du
http://localhost:4200
för att öppna programmet.Välj knappen Inloggning i det övre högra hörnet på skärmen.
När du har loggat in visas din profilinformation på sidan.
Välj knappen Logga ut i det övre högra hörnet på skärmen för att logga ut.
Se även
När du har slutfört den här självstudien kanske du vill veta mer om hur du: