教學課程:建立 Angular 應用程式並準備進行驗證
適用於:白色核取號的 工作力租用者
外部租用者(了解更多)
本教學課程是一系列的第一個部分,示範如何使用Microsoft身分識別平臺建置 Angular 單頁應用程式(SPA),新增驗證和擷取用戶數據。
在本教學課程中:
- 建立新的 Angular 專案
- 設定應用程式的設定
- 將驗證程式碼新增至應用程式
必要條件
- Angular CLI
- Node.js。
- Visual Studio Code 或其他程式碼編輯器。
- Microsoft Entra 系統管理中心內具有下列設定的新應用程式註冊。 如需詳細資訊,請參閱 註冊應用程式。
- 名稱:identity-client-spa
- 支援的帳戶類型:僅限此組織目錄中的 帳戶(單一租使用者)。
- 平台組態:單頁應用程式 (SPA)。
-
重新導向 URI:
http://localhost:4200/
。
- (僅外部使用)一個已與您的應用程式註冊相關聯的使用者流程。 如需詳細資訊,請參閱 為外部租使用者中的應用程式建立自助式註冊使用者流程, 和 將應用程式新增至使用者流程。
建立新的 Angular 專案
在本節中,您將使用 Visual Studio Code 中的 Angular CLI 建立新的 Angular 專案。 根據您的租用戶類型選擇合適的標籤。
若要從頭開始建置 Angular 專案,請遵循下列步驟:
開啟終端機視窗,然後執行下列命令來建立新的 Angular 專案:
ng new msal-angular-tutorial --routing=true --style=css --strict=false
此命令會建立名為
msal-angular-tutorial
的新 Angular 專案,並啟用路由、設定樣式的 CSS,以及停用嚴格模式。變更為專案目錄:
cd msal-angular-tutorial
安裝應用程式相依性:
npm install @azure/msal-browser @azure/msal-angular bootstrap
此命令
npm install @azure/msal-browser @azure/msal-angular bootstrap
會安裝 Azure MSAL 瀏覽器、Azure MSAL Angular 和 Bootstrap 套件。開啟
angular.json
並將 Bootstrap 的 CSS 路徑新增至styles
陣列:"styles": [ "src/styles.css", "node_modules/bootstrap/dist/css/bootstrap.min.css" ],
程序代碼會將 Bootstrap CSS 新增至檔案中的
angular.json
樣式陣列。產生首頁與設定檔元件:
ng generate component home ng generate component profile
命令會在 Angular 專案中產生 Home 和 Profile 元件。
從項目移除不必要的檔案和程式碼:
rm src/app/app.component.css rm src/app/app.component.spec.ts rm src/app/home/home.component.css rm src/app/home/home.component.spec.ts rm src/app/profile/profile.component.css rm src/app/profile/profile.component.spec.ts
命令會從專案中移除不必要的檔案和程序代碼。
使用Visual Studio Code將
app.routes.ts
重新命名為app-routing.module.ts
,並更新整個應用程式中所有app.routes.ts
的參考。將
app.config.ts
重新命名為app.module.ts
,並使用 Visual Studio Code 更新應用程式中所有對app.config.ts
的參考。
完成這些步驟之後,項目結構看起來應該像這樣:
.
├── README.md
├── angular.json
├── package-lock.json
├── package.json
├── src
│ ├── app
│ │ ├── app-routing.module.ts
│ │ ├── app.component.html
│ │ ├── app.component.ts
│ │ ├── app.module.ts
│ │ ├── home
│ │ │ ├── home.component.html
│ │ │ └── home.component.ts
│ │ └── profile
│ │ ├── profile.component.html
│ │ └── profile.component.ts
│ ├── index.html
│ ├── main.ts
│ ├── polyfills.ts
│ └── styles.css
├── tsconfig.app.json
└── tsconfig.json
設定應用程式設定
在本節中,您將設定驗證的應用程式設定。 我們將使用應用程式註冊期間記錄的值來設定應用程式以進行驗證。 根據您的租戶類型,選擇合適的選項卡。
我們將使用應用程式註冊期間記錄的值來設定應用程式以進行驗證。 執行下列步驟:
請開啟
src/app/app.module.ts
檔案,並以下列代碼取代內容:// Required for Angular multi-browser support import { BrowserModule } from '@angular/platform-browser'; // Required for Angular import { NgModule } from '@angular/core'; // Required modules and components for this application import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { ProfileComponent } from './profile/profile.component'; import { HomeComponent } from './home/home.component'; // HTTP modules required by MSAL import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http'; // Required for MSAL import { IPublicClientApplication, PublicClientApplication, InteractionType, BrowserCacheLocation, LogLevel } from '@azure/msal-browser'; import { MsalGuard, MsalInterceptor, MsalBroadcastService, MsalInterceptorConfiguration, MsalModule, MsalService, MSAL_GUARD_CONFIG, MSAL_INSTANCE, MSAL_INTERCEPTOR_CONFIG, MsalGuardConfiguration, MsalRedirectComponent } from '@azure/msal-angular'; const isIE = window.navigator.userAgent.indexOf('MSIE ') > -1 || window.navigator.userAgent.indexOf('Trident/') > -1; export function MSALInstanceFactory(): IPublicClientApplication { return new PublicClientApplication({ auth: { // 'Application (client) ID' of app registration in the Microsoft Entra admin center - this value is a GUID clientId: "Enter_the_Application_Id_Here", // Full directory URL, in the form of https://login.microsoftonline.com/<tenant> authority: "https://login.microsoftonline.com/Enter_the_Tenant_Info_Here", // Must be the same redirectUri as what was provided in your app registration. redirectUri: "http://localhost:4200", }, cache: { cacheLocation: BrowserCacheLocation.LocalStorage, storeAuthStateInCookie: isIE } }); } // MSAL Interceptor is required to request access tokens in order to access the protected resource (Graph) export function MSALInterceptorConfigFactory(): MsalInterceptorConfiguration { const protectedResourceMap = new Map<string, Array<string>>(); protectedResourceMap.set('https://graph.microsoft.com/v1.0/me', ['user.read']); return { interactionType: InteractionType.Redirect, protectedResourceMap }; } // MSAL Guard is required to protect routes and require authentication before accessing protected routes export function MSALGuardConfigFactory(): MsalGuardConfiguration { return { interactionType: InteractionType.Redirect, authRequest: { scopes: ['user.read'] } }; } // Create an NgModule that contains the routes and MSAL configurations @NgModule({ declarations: [ AppComponent, HomeComponent, ProfileComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule, MsalModule ], providers: [ { provide: HTTP_INTERCEPTORS, useClass: MsalInterceptor, multi: true }, { provide: MSAL_INSTANCE, useFactory: MSALInstanceFactory }, { provide: MSAL_GUARD_CONFIG, useFactory: MSALGuardConfigFactory }, { provide: MSAL_INTERCEPTOR_CONFIG, useFactory: MSALInterceptorConfigFactory }, MsalService, MsalGuard, MsalBroadcastService ], bootstrap: [AppComponent, MsalRedirectComponent] }) export class AppModule { }
程式代碼會設定 MSAL 以進行使用者驗證和 API 保護。 它會將應用程式設定成使用
MsalInterceptor
來保護 API 請求和使用MsalGuard
來保護路由,同時定義驗證所需的關鍵元件和服務。 將下列值取代為來自 Microsoft Entra 系統管理中心的值。- 將
Enter_the_Application_Id_Here
替換為應用程式註冊中的Application (client) ID
。 - 將
Enter_the_Tenant_Info_Here
替換為來自應用程式註冊的Directory (tenant) ID
。
- 將
儲存檔案。
將驗證程式碼新增至應用程式
在本節中,您會將驗證碼新增至應用程式,以處理使用者驗證和會話管理。 根據您的租客類型選擇適當的標籤。
開啟
src/app/app.component.ts
檔案,並以下列程式代碼取代內容:// Required for Angular import { Component, OnInit, Inject, OnDestroy } from '@angular/core'; // Required for MSAL import { MsalService, MsalBroadcastService, MSAL_GUARD_CONFIG, MsalGuardConfiguration } from '@azure/msal-angular'; import { EventMessage, EventType, InteractionStatus, RedirectRequest } from '@azure/msal-browser'; // Required for RJXS import { Subject } from 'rxjs'; import { filter, takeUntil } from 'rxjs/operators'; @Component({ selector: 'app-root', templateUrl: './app.component.html' }) export class AppComponent implements OnInit, OnDestroy { title = 'Angular - MSAL Example'; loginDisplay = false; tokenExpiration: string = ''; private readonly _destroying$ = new Subject<void>(); constructor( @Inject(MSAL_GUARD_CONFIG) private msalGuardConfig: MsalGuardConfiguration, private authService: MsalService, private msalBroadcastService: MsalBroadcastService ) { } // On initialization of the page, display the page elements based on the user state ngOnInit(): void { this.msalBroadcastService.inProgress$ .pipe( filter((status: InteractionStatus) => status === InteractionStatus.None), takeUntil(this._destroying$) ) .subscribe(() => { this.setLoginDisplay(); }); // Used for storing and displaying token expiration this.msalBroadcastService.msalSubject$.pipe(filter((msg: EventMessage) => msg.eventType === EventType.ACQUIRE_TOKEN_SUCCESS)).subscribe(msg => { this.tokenExpiration= (msg.payload as any).expiresOn; localStorage.setItem('tokenExpiration', this.tokenExpiration); }); } // If the user is logged in, present the user with a "logged in" experience setLoginDisplay() { this.loginDisplay = this.authService.instance.getAllAccounts().length > 0; } // Log the user in and redirect them if MSAL provides a redirect URI otherwise go to the default URI login() { if (this.msalGuardConfig.authRequest) { this.authService.loginRedirect({ ...this.msalGuardConfig.authRequest } as RedirectRequest); } else { this.authService.loginRedirect(); } } // Log the user out logout() { this.authService.logoutRedirect(); } ngOnDestroy(): void { this._destroying$.next(undefined); this._destroying$.complete(); } }
程式代碼整合 MSAL 與 Angular 來管理用戶驗證。 它會監聽登入狀態的變更、顯示登入狀態、處理令牌取得事件,並提供根據 Microsoft Entra 組態進行用戶登入或登出的功能。
儲存檔案。