適用於: 工作團隊租戶
外部租戶(深入瞭解)
本教學課程是一系列的最後一部分,示範如何使用 Microsoft 身分識別平臺建置 Angular 單頁應用程式 (SPA) 和新增驗證。 在此系列 的第 2 部分中,您已建立了 Angular SPA,並已為工作群租戶的驗證做好準備。
在本教學指南中,您將會
- 將數據處理新增至 Angular 應用程式。
- 測試應用程式並擷取用戶數據。
先決條件
擷取數據以在應用程式UI中檢視
若要設定 Angular 應用程式以與 Microsoft Graph API 互動,請完成下列步驟:
開啟
src/app/profile/profile.component.ts
檔案,並以下列代碼段取代內容:// Required for Angular import { Component, OnInit } from '@angular/core'; // Required for the HTTP GET request to Graph import { HttpClient } from '@angular/common/http'; type ProfileType = { businessPhones?: string, displayName?: string, givenName?: string, jobTitle?: string, mail?: string, mobilePhone?: string, officeLocation?: string, preferredLanguage?: string, surname?: string, userPrincipalName?: string, id?: string } @Component({ selector: 'app-profile', templateUrl: './profile.component.html' }) export class ProfileComponent implements OnInit { profile!: ProfileType; tokenExpiration!: string; constructor( private http: HttpClient ) { } // When the page loads, perform an HTTP GET request from the Graph /me endpoint ngOnInit() { this.http.get('https://graph.microsoft.com/v1.0/me') .subscribe(profile => { this.profile = profile; }); this.tokenExpiration = localStorage.getItem('tokenExpiration')!; } }
Angular 中的
ProfileComponent
會從 Microsoft Graph/me
端點擷取使用者配置檔數據。 它會定義ProfileType
這類結構屬性,例如displayName
和mail
。 在ngOnInit
中,它會使用HttpClient
傳送 GET 要求,將回應指派給profile
。 它也會從localStorage
中擷取並儲存tokenExpiration
的令牌到期時間。開啟
src/app/profile/profile.component.html
檔案,並以下列代碼段取代內容:<div class="profile"> <p><strong>Business Phones:</strong> {{profile?.businessPhones}}</p> <p><strong>Display Name:</strong> {{profile?.displayName}}</p> <p><strong>Given Name:</strong> {{profile?.givenName}}</p> <p><strong>Job Title:</strong> {{profile?.jobTitle}}</p> <p><strong>Mail:</strong> {{profile?.mail}}</p> <p><strong>Mobile Phone:</strong> {{profile?.mobilePhone}}</p> <p><strong>Office Location:</strong> {{profile?.officeLocation}}</p> <p><strong>Preferred Language:</strong> {{profile?.preferredLanguage}}</p> <p><strong>Surname:</strong> {{profile?.surname}}</p> <p><strong>User Principal Name:</strong> {{profile?.userPrincipalName}}</p> <p><strong>Profile Id:</strong> {{profile?.id}}</p> <br><br> <p><strong>Token Expiration:</strong> {{tokenExpiration}}</p> <br><br> <p>Refreshing this page will continue to use the cached access token until it nears expiration, at which point a new access token will be requested.</p> </div>
此程式代碼會定義顯示使用者配置檔資訊的 HTML 範本,使用 Angular 的插補語法系結來自
profile
物件的屬性(例如,businessPhones
、displayName
、jobTitle
)。 它還顯示tokenExpiration
值,並附上說明指出,重新整理頁面將使用快取的存取令牌,直至該令牌接近過期,然後才會請求新的令牌。
測試應用程式
若要讓應用程式運作,您必須執行 Angular 應用程式並登入,以向您的 Microsoft Entra 租使用者進行驗證,並擷取用戶數據。
若要測試應用程式,請完成下列步驟:
在終端機中執行下列命令,以執行 Angular 應用程式:
ng serve --open
選取 登入 按鈕,以向您的 Microsoft Entra 租戶進行驗證。
登入之後,選取 [檢視配置檔] 連結,以流覽至 [配置檔] 頁面。 確認顯示使用者檔案資訊,包括使用者的名稱、電子郵件、職稱和其他細節。
選取 註銷 按鈕以登出應用程式。
後續步驟
透過嘗試以下教學課程系列,學習如何使用 Microsoft 身分識別平台,並建置 Web API。