자습서: 외부 테넌트에 대한 Angular SPA에 로그인 및 로그아웃 추가
이 자습서는 Angular SPA(단일 페이지 애플리케이션)를 빌드하고 Microsoft Entra 관리 센터를 사용하여 인증을 준비하는 방법을 보여 주는 시리즈의 마지막 부분입니다. 이 시리즈 3부에서는 Angular 단일 페이지 애플리케이션에 인증 흐름을 추가하고 외부 테넌트에서 작동하도록 흐름을 구성했습니다. 이 문서에서는 애플리케이션에 로그인 및 로그아웃 기능을 추가하는 방법을 알아봅니다. 마지막으로 애플리케이션을 테스트합니다.
이 자습서에서는 다음을 수행합니다.
- 앱에 로그인 및 로그아웃 기능을 추가합니다.
- 애플리케이션 테스트
필수 조건
사용자 로그인 및 로그아웃
src/app/app.component.ts를 열고 코드를 다음으로 바꿔 POP(point of presence)-up을 사용하여 사용자를 로그인합니다. 이 코드는 MSAL Angular 라이브러리를 사용하여 사용자를 로그인합니다.
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(); } }
애플리케이션 테스트
애플리케이션 폴더의 명령줄 프롬프트에서 다음 명령을 실행하여 웹 서버를 시작합니다.
npm install npm start
브라우저에서
http://localhost:4200
를 입력하여 애플리케이션을 엽니다.화면의 오른쪽 위 모서리에서 로그인 단추를 선택합니다.
로그인하면 페이지에 프로필 정보가 표시됩니다.
화면의 오른쪽 위 모서리에 있는 로그아웃 단추를 선택하여 로그아웃합니다.
참고 항목
이 자습서를 완료한 후에는 다음 방법에 대해 자세히 알아볼 수 있습니다.