適用於:
員工租戶
外部租用戶 (深入瞭解)
本教學課程是一系列的第 2 部分,示範如何使用 Microsoft 身分識別平臺建置 Angular 單頁應用程式 (SPA) 和新增驗證。 在 本系列的第 1 部分中,您已建立 Angular SPA 並新增初始設定。
在本教學課程中,您會:
- 新增登入和登出
必要條件
- 完成前提條件和步驟 for 教程:建立 Angular 單頁應用程式
將登入和註銷功能新增至您的應用程式
在本節中,您將新增元件以支援 Angular 應用程式中的登入和註銷功能。 這些元件可讓使用者驗證和管理其工作階段。 您將根據應用程式的驗證狀態,將路由新增至應用程式,以將使用者導向適當的元件。
若要在 Angular 應用程式中啟用登入和註銷功能,請遵循下列步驟:
打開
src/app/app.component.html檔案,然後用以下程式代碼取代其內容。<a class="navbar navbar-dark bg-primary" variant="dark" href="/"> <a class="navbar-brand"> Microsoft Identity Platform </a> <a> <button *ngIf="!loginDisplay" class="btn btn-secondary" (click)="login()">Sign In</button> <button *ngIf="loginDisplay" class="btn btn-secondary" (click)="logout()">Sign Out</button> </a> </a> <a class="profileButton"> <a [routerLink]="['profile']" class="btn btn-secondary" *ngIf="loginDisplay">View Profile</a> </a> <div class="container"> <router-outlet></router-outlet> </div>程序代碼會在 Angular 應用程式中實作導覽列。 它會根據使用者驗證狀態動態顯示 [登入 ] 和 [註銷 ] 按鈕,並包含 登入使用者的 [檢視配置檔 ] 按鈕,以增強應用程式的使用者介面。 當按鈕被選取時,會呼叫
login()中的logout()和src/app/app.component.ts方法。打開
src/app/app-routing.module.ts檔案,然後用以下程式代碼取代其內容。// Required for Angular import { NgModule } from '@angular/core'; // Required for the Angular routing service import { Routes, RouterModule } from '@angular/router'; // Required for the "Profile" page import { ProfileComponent } from './profile/profile.component'; // Required for the "Home" page import { HomeComponent } from './home/home.component'; // MsalGuard is required to protect routes and require authentication before accessing protected routes import { MsalGuard } from '@azure/msal-angular'; // Define the possible routes // Specify MsalGuard on routes to be protected // '**' denotes a wild card const routes: Routes = [ { path: 'profile', component: ProfileComponent, canActivate: [ MsalGuard ] }, { path: '**', component: HomeComponent } ]; // Create an NgModule that contains all the directives for the routes specified above @NgModule({ imports: [RouterModule.forRoot(routes, { useHash: true })], exports: [RouterModule] }) export class AppRoutingModule { }代碼段會藉由建立 Profile 和 Home 元件的路徑,在 Angular 應用程式中設定路由。 它會使用
MsalGuard在個人資料路由上強制執行驗證,而所有不相符的路徑都會重新導向至 首頁 元件。打開
src/app/home/home.component.ts檔案,然後用以下程式代碼取代其內容。// Required for Angular import { Component, OnInit } from '@angular/core'; // Required for MSAL import { MsalBroadcastService, MsalService } from '@azure/msal-angular'; // Required for Angular multi-browser support import { EventMessage, EventType, AuthenticationResult } from '@azure/msal-browser'; // Required for RJXS observables import { filter } from 'rxjs/operators'; @Component({ selector: 'app-home', templateUrl: './home.component.html' }) export class HomeComponent implements OnInit { constructor( private authService: MsalService, private msalBroadcastService: MsalBroadcastService ) { } // Subscribe to the msalSubject$ observable on the msalBroadcastService // This allows the app to consume emitted events from MSAL ngOnInit(): void { this.msalBroadcastService.msalSubject$ .pipe( filter((msg: EventMessage) => msg.eventType === EventType.LOGIN_SUCCESS), ) .subscribe((result: EventMessage) => { const payload = result.payload as AuthenticationResult; this.authService.instance.setActiveAccount(payload.account); }); } }程式代碼會設定名為
HomeComponent的 Angular 元件,該元件會與 Microsoft 驗證連結庫 (MSAL) 整合。 在ngOnInit生命周期勾子中,元件會訂閱來自msalSubject$的MsalBroadcastServiceObservable,並篩選出登入成功事件。 當登入事件發生時,它會擷取驗證結果,並在MsalService中設定使用中的帳戶,讓應用程式能夠管理用戶會話。打開
src/app/home/home.component.html檔案,然後用以下程式代碼取代其內容。<div class="title"> <h5> Welcome to the Microsoft Authentication Library For JavaScript - Angular SPA </h5> <p >View your data from Microsoft Graph by clicking the "View Profile" link above.</p> </div>此程式代碼會歡迎使用者前往應用程式,並提示他們按兩下 [檢視配置檔 ] 連結來檢視其Microsoft圖形數據。
打開
src/main.ts檔案,然後用以下程式代碼取代其內容。import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; platformBrowserDynamic().bootstrapModule(AppModule) .catch(err => console.error(err));這段代碼是將
platformBrowserDynamic從 Angular 的平台瀏覽器動態模組,以及將AppModule從應用程式的模組檔案中匯入。 然後,它會使用platformBrowserDynamic()來啟動AppModule,初始化 Angular 應用程式。 引導過程中發生的任何錯誤都會被攔截並記錄在控制台。打開
src/index.html檔案,然後用以下程式代碼取代其內容。<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>MSAL For JavaScript - Angular SPA</title> </head> <body> <app-root></app-root> <app-redirect></app-redirect> </body> </html>這段程式碼定義了一個 HTML5 文件,使用英文作為語言和 UTF-8 作為字元編碼。 它會將標題設定為「MSAL For JavaScript - Angular SPA」。內文包含
<app-root>元件作為主要進入點,以及<app-redirect>元件作為重新導向功能。打開
src/styles.css檔案,然後用以下程式代碼取代其內容。body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } code { font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', monospace; } .app { text-align: center; padding: 8px; } .title{ text-align: center; padding: 18px; } .profile{ text-align: center; padding: 18px; } .profileButton{ display: flex; justify-content: center; padding: 18px; }CSS 程式代碼會將網頁的字型設定為新式 sans-serif 字型、移除預設邊界,以及套用字體平滑處理,以增強可讀性來設定網頁樣式。 它會將文字在
.app、.title和.profile類別中置中並添加內距,而.profileButton類別則使用 flexbox 將其元素置中。