適用対象:
外部テナント (詳細)
このチュートリアルでは、ネイティブ認証 JavaScript SDK を使用して、Angular シングルページ アプリ (SPA) にユーザーをサインインさせる方法について説明します。
このチュートリアルでは、次の操作を行います。
- Angular アプリを更新してユーザーをサインインさせる。
- サインイン フローをテストします。
[前提条件]
サインイン コンポーネントを作成する
Angular CLI を使用して、次のコマンドを実行して 、components フォルダー内のサインイン ページ用の新しいコンポーネントを生成します。
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の次のロジックは、最初のサインイン試行後の次の手順を決定します。 結果に応じて、サインイン プロセスの適切な部分をユーザーに案内するために 、パスワード または 1 回限りのコード フォームが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 プロキシ サーバーを起動するには、ターミナルで次のコマンドを実行します。
npm run corsAngular アプリを起動するには、別のターミナル ウィンドウを開き、次のコマンドを実行します。
npm startWeb ブラウザーを開き、
http://localhost:4200/sign-inに移動します。 サインイン フォームが表示されます。既存のアカウントにサインインするには、詳細を入力し、[サインイン] ボタンを選択し、プロンプトに従います。
エイリアスまたはユーザー名を使用してサインインを有効にする
メール アドレスとパスワードを使用してサインインするユーザーも、ユーザー名とパスワードでサインインできます。 代替サインイン識別子とも呼ばれるユーザー名には、顧客 ID、アカウント番号、またはユーザー名として使用する別の識別子を指定できます。
Microsoft Entra 管理センターを使用してユーザー アカウントにユーザー名を手動で割り当てたり、Microsoft Graph API を使用してアプリで自動化したりできます。
「エイリアスまたはユーザー名を使用してサインインする」の記事の手順を使用して、ユーザーがアプリケーションでユーザー名を使用してサインインできるようにします。
- サインインでユーザー名を有効にします。
- 管理センターでユーザー名を持つユーザーを作成するか、ユーザー名 を 追加して既存のユーザーを更新します。 または、 Microsoft Graph API を使用して、アプリでのユーザーの作成と更新を自動化することもできます。