適用於:
外部租用戶 (深入瞭解)
在本教學課程中,您將瞭解如何使用原生驗證 JavaScript SDK 將使用者登入 Angular 單頁應用程式 (SPA)。
在本教學課程中,您會:
- 更新 Angular 應用程式以登入使用者。
- 測試登入流程。
先決條件
建立登入元件
執行下列命令,使用 Angular CLI 產生 元件 資料夾內登入頁面的新元件:
cd components ng generate component sign-in開啟登入/sign-in.component.ts檔案,並以來自sign-in.component.ts的內容取代其內容
開啟 登入/sign-in.component.html 檔案,然後從 sign-in.component.html新增內容。
sign-in.component.ts中的下列邏輯會決定初始登入嘗試之後的下一個步驟。 視結果而定,它會在 sign-in.component.html 中顯示密碼或單次程式代碼表單體,以引導使用者完成登入程式的適當部分:
const result: SignInResult = await client.signIn({ username: this.username }); if (result.isPasswordRequired()) { this.showPassword = true; this.showCode = false; } else if (result.isCodeRequired()) { this.showPassword = false; this.showCode = true; } else if (result.isCompleted()) { this.isSignedIn = true; this.userData = result.data; }SDK 的實例方法
signIn()會啟動登入流程。在 sign-in.component.html 檔案中:
<form *ngIf="showPassword" (ngSubmit)="submitPassword()"> <input type="password" [(ngModel)]="password" name="password" placeholder="Password" required /> <button type="submit" [disabled]="loading">{{ loading ? 'Verifying...' : 'Submit Password' }}</button> </form> <form *ngIf="showCode" (ngSubmit)="submitCode()"> <input type="text" [(ngModel)]="code" name="code" placeholder="OTP Code" required /> <button type="submit" [disabled]="loading">{{ loading ? 'Verifying...' : 'Submit Code' }}</button> </form>
更新路由模組
開啟 src/app/app.routes.ts 檔案,然後新增登入元件的路由:
import { SignInComponent } from './components/sign-in/sign-in.component';
export const routes: Routes = [
...
{ path: 'sign-in', component: SignInComponent },
];
測試登入功能
若要啟動 CORS Proxy 伺服器,請在終端機中執行下列命令:
npm run cors若要啟動 Angular 應用程式,請開啟另一個終端機視窗,然後執行下列命令:
npm start開啟 web 瀏覽器並巡覽至
http://localhost:4200/sign-in。 登入表單隨即出現。若要登入現有的帳戶,請輸入您的詳細數據,選取 [登入] 按鈕,然後遵循提示。
啟用別名或使用者名稱登入
您可以允許使用電子郵件地址和密碼登入的使用者也使用使用者名稱和密碼登入。 使用者名稱也稱為替代登入識別碼,可以是客戶 ID、帳號,或你選擇使用的其他識別碼作為使用者名稱。
你可以透過 Microsoft Entra 管理中心手動指派使用者名稱給使用者帳號,或透過 Microsoft Graph API 自動化流程。
請使用「 以別名或使用者名稱登入 」文章中的步驟,讓你的使用者能在應用程式中使用使用者名登入: