React Webサイト認証
React Webサイト認証ジェネレーターは、Amazon Cognitoを使用してReact Webサイトに認証を追加します。
このジェネレーターは、Cognito User Poolとそれに関連するIdentity Pool、ユーザーログインフローを処理するホストされたUI、およびReact Webサイトとの統合を作成するためのCDKまたはTerraformインフラストラクチャを構成します。
React Webサイトに認証を追加する
Section titled “React Webサイトに認証を追加する”React Webサイトに認証を追加するには、2つの方法があります:
pnpm nx g @aws/nx-plugin:ts#website#authyarn nx g @aws/nx-plugin:ts#website#authnpx nx g @aws/nx-plugin:ts#website#authbunx nx g @aws/nx-plugin:ts#website#auth変更されるファイルを確認するためにドライランを実行することもできます
pnpm nx g @aws/nx-plugin:ts#website#auth --dry-runyarn nx g @aws/nx-plugin:ts#website#auth --dry-runnpx nx g @aws/nx-plugin:ts#website#auth --dry-runbunx nx g @aws/nx-plugin:ts#website#auth --dry-run- インストール Nx Console VSCode Plugin まだインストールしていない場合
- VSCodeでNxコンソールを開く
- クリック
Generate (UI)"Common Nx Commands"セクションで - 検索
@aws/nx-plugin - ts#website#auth - 必須パラメータを入力
- クリック
Generate
| パラメータ | 型 | デフォルト | 説明 |
|---|---|---|---|
| project 必須 | string | - | ウェブサイトのルートディレクトリ。 |
| cognitoDomain | string | - | 使用するCognitoドメインプレフィックス。省略した場合、npmスコープとウェブサイトプロジェクト名から値が導出されます。 |
| allowSignup | boolean | 自己サインアップを許可するかどうか | |
| iac | inherit | cdk | terraform | inherit | 優先するIaCプロバイダー。デフォルトでは、初期選択から継承されます。 |
| preferInstallDependencies | boolean | true | ジェネレーター実行後に依存関係のインストールを優先するかどうか。複数のジェネレーターをバッチ処理する際にインストールを延期する場合はfalseに設定します(後続のジェネレーターがNxプロジェクトグラフを計算できるよう、必要に応じてインストールは実行されます)。最後に一度だけインストールします。 |
ジェネレーター出力
Section titled “ジェネレーター出力”React Webサイトに以下の変更が加えられます:
Directorysrc
Directorycomponents
DirectoryCognitoAuth
- index.tsx Main authentication component
- main.tsx Updated to instrument the CognitoAuth component
インフラストラクチャ
Section titled “インフラストラクチャ”このジェネレーターは、選択した iac に基づいてインフラストラクチャをコードとして提供するため、関連する CDK コンストラクトまたは Terraform モジュールを含む packages/common にプロジェクトを作成します。
共通のインフラストラクチャコードプロジェクトは、次のように構成されています:
Directorypackages/common/constructs
Directorysrc
Directoryapp/ プロジェクト/ジェネレーター固有のインフラストラクチャ用のコンストラクト
- …
Directorycore/
app内のコンストラクトによって再利用される汎用コンストラクト- …
- index.ts
appからコンストラクトをエクスポートするエントリーポイント
- project.json プロジェクトのビルドターゲットと設定
Directorypackages/common/terraform
Directorysrc
Directoryapp/ プロジェクト/ジェネレーター固有のインフラストラクチャ用の Terraform モジュール
- …
Directorycore/
app内のモジュールによって再利用される汎用モジュール- …
- project.json プロジェクトのビルドターゲットと設定
選択したiacに基づいて、以下のインフラストラクチャコードも生成されます:
Directorypackages/common/constructs/src
Directorycore
- user-identity.ts Construct which defines the user pool and identity pool
Directorypackages/common/terraform/src
Directorycore
Directoryuser-identity
- main.tf Module wrapper for the identity configuration
Directoryidentity
- identity.tf Core identity infrastructure including Cognito User Pool and Identity Pool
Directoryadd-callback-url
- add-callback-url.tf Module for adding callback URLs to existing user pool clients
アーキテクチャ
Section titled “アーキテクチャ”このジェネレーターは、既存の静的Webサイトアーキテクチャに、Amazon Cognito User Pool(サインイン用)とIdentity Pool(サインインしたユーザーをスコープ付きIAM認証情報にフェデレートするため)を追加します:
User Poolは、Cognito Plus機能プランで作成され、標準認証の脅威保護がAUDITモードに設定されています。監査モードでは、Cognitoは各サインインにリスクレベルを割り当て、ユーザーをブロックすることなく評価をCloudWatchに記録します。
ユーザーのリスク評価を観察した後、完全機能の強制に切り替えて、リスクの高いアクティビティに自動的に対応できます(例:MFAの要求やサインインのブロック):
packages/common/constructs/src/core/user-identity.tsでstandardThreatProtectionModeをStandardThreatProtectionMode.FULL_FUNCTIONに設定します。
packages/common/terraform/src/core/user-identity/identity/identity.tfのuser_pool_add_onsブロックでadvanced_security_modeをENFORCEDに設定します。
多要素認証(MFA)
Section titled “多要素認証(MFA)”デフォルトでは、ユーザーはサインインする前にMFA(SMSコードまたは時間ベースのワンタイムパスワード)を設定する必要があります。MFAをオプションにしたり、完全にオフにしたり、利用可能な第2要素の方法を制限したりできます:
import { Mfa } from 'aws-cdk-lib/aws-cognito';
new UserIdentity(this, 'Identity', { mfa: Mfa.OPTIONAL, mfaSecondFactor: { sms: false, otp: true },});mfaはMfa.OFF / Mfa.OPTIONAL / Mfa.REQUIREDを受け入れます。mfaSecondFactor.smsとmfaSecondFactor.otpは、各第2要素の方法を個別に有効または無効にします。mfaがMfa.OFFの場合、これらは効果がありません。mfa: Mfa.REQUIREDを設定し、両方の方法を無効にすると、誰もサインインを完了できなくなるため、synth時に拒否されます。
module "user_identity" { source = "../../common/terraform/src/core/user-identity"
mfa = "OPTIONAL" mfa_second_factor_sms = false mfa_second_factor_otp = true}mfaは"OFF" / "OPTIONAL" / "ON"を受け入れます。mfa_second_factor_smsとmfa_second_factor_otpは、各第2要素の方法を個別に有効または無効にします。mfaが"OFF"の場合、これらは効果がありません。
Webアプリケーションファイアウォール(WAF)
Section titled “Webアプリケーションファイアウォール(WAF)”デフォルトでは、User PoolはAWSManagedRulesCommonRuleSetとAWSManagedRulesKnownBadInputsRuleSetマネージドルールグループを使用するAWS WAFv2 Web ACLに関連付けられています。独自のWeb ACLを管理したい場合や、必要ない場合は、これを無効にできます:
new UserIdentity(this, 'Identity', { enableWaf: false });module "user_identity" { source = "../../common/terraform/src/core/user-identity"
enable_waf = false}インフラストラクチャの使用方法
Section titled “インフラストラクチャの使用方法”スタックにユーザーIDインフラストラクチャを追加する必要があります。Webサイトの_前に_宣言してください:
import { Stack } from 'aws-cdk-lib';import { Construct } from 'constructs';import { MyWebsite, UserIdentity } from '@my-scope/common-constructs';
export class ApplicationStack extends Stack { constructor(scope: Construct, id: string) { super(scope, id);
new UserIdentity(this, 'Identity');
new MyWebsite(this, 'MyWebsite'); }}UserIdentityコンストラクトは、Webサイトが認証のために正しいCognito User Poolを指すように、必要なランタイム設定を自動的に追加します。
ユーザーIDモジュールを追加し、Webサイトがそれに依存するようにする必要があります:
# Deploy user identity first to add to runtime configmodule "user_identity" { source = "../../common/terraform/src/core/user-identity"}
# Deploy website after identity to include runtime configmodule "my_website" { source = "../../common/terraform/src/app/static-websites/my-website"
providers = { aws.us_east_1 = aws.us_east_1 }
# Ensure identity is deployed first to add to runtime config depends_on = [module.user_identity]}ユーザーIDモジュールは、Webサイトが認証のために正しいCognito User Poolを指すように、必要なランタイム設定を自動的に追加します。
認証されたユーザーへのアクセス許可
Section titled “認証されたユーザーへのアクセス許可”APIの呼び出し権限の付与など、認証されたユーザーが特定のアクションを実行できるようにするには、Identity Poolの認証済みロールにIAMポリシーステートメントを追加できます:
import { Stack } from 'aws-cdk-lib';import { Construct } from 'constructs';import { MyWebsite, UserIdentity, MyApi } from '@my-scope/common-constructs';
export class ApplicationStack extends Stack { constructor(scope: Construct, id: string) { super(scope, id);
const identity = new UserIdentity(this, 'Identity'); const api = new MyApi(this, 'MyApi', { integrations: MyApi.defaultIntegrations(this).build(), });
api.grantInvokeAccess(identity.identityPool.authenticatedRole);
new MyWebsite(this, 'MyWebsite'); }}module "user_identity" { source = "../../common/terraform/src/core/user-identity"}
module "asset_bucket" { source = "../../common/terraform/src/core/asset-bucket"}
module "my_api" { source = "../../common/terraform/src/app/apis/my-api"
asset_bucket_name = module.asset_bucket.bucket_name}
# Add permissions for authenticated users to invoke Fast APIresource "aws_iam_role_policy" "authenticated_fast_api_invoke" { name = "authenticated-user-invoke-my-api" role = module.user_identity.authenticated_role_name
policy = jsonencode({ Version = "2012-10-17" Statement = [ { Effect = "Allow" Action = [ "execute-api:Invoke" ] Resource = "${module.my_api.api_execution_arn}/*" } ] })}