適用於:
外部租用戶 (深入瞭解)
在本教學課程中,您將瞭解如何使用原生驗證 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()會啟動登入流程。
備註
當租戶的使用者流程啟用
username內建使用者屬性時,該參數會接受使用者的電子郵件地址或使用者名稱(別名)。 使用者可以輸入任一值來登入。 要啟用該屬性,請參見 登入識別碼政策中的啟用使用者名稱。- 在 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>- SDK 的實例方法
更新路由模組
開啟 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。 登入表單隨即出現。若要登入現有的帳戶,請輸入您的詳細數據,選取 [登入] 按鈕,然後遵循提示。