React 网站身份验证
React 网站身份验证生成器使用 Amazon Cognito 为您的 React 网站添加身份验证。
此生成器配置 CDK 或 Terraform 基础设施以创建 Cognito 用户池和关联的身份池,以及用于处理用户登录流程的托管 UI,并将其与您的 React 网站集成。
为您的 React 网站添加身份验证
Section titled “为您的 React 网站添加身份验证”您可以通过两种方式为 React 网站添加身份验证:
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- 安装 Nx Console VSCode Plugin 如果您尚未安装
- 在VSCode中打开Nx控制台
- 点击
Generate (UI)在"Common Nx Commands"部分 - 搜索
@aws/nx-plugin - ts#website#auth - 填写必需参数
- 点击
Generate
| 参数 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| project 必需 | string | - | 网站的根目录。 |
| cognitoDomain | string | - | 要使用的 Cognito 域前缀。如果省略,将从 npm scope 和网站项目名称派生一个值。 |
| allowSignup | boolean | 是否允许自助注册 | |
| iac | inherit | cdk | terraform | inherit | 首选的 IaC 提供商。默认情况下,这继承自您的初始选择。 |
| preferInstallDependencies | boolean | true | 是否在生成器运行后优先安装依赖项。设置为 false 可在批量运行多个生成器时延迟安装(如果后续生成器需要计算 Nx 项目图,仍会运行安装);在最后统一安装一次。 |
您将在 React 网站中找到以下更改:
文件夹src
文件夹components
文件夹CognitoAuth
- index.tsx Main authentication component
- main.tsx Updated to instrument the CognitoAuth component
由于此生成器根据您选择的 iac 提供基础设施即代码,它将在 packages/common 中创建一个项目,其中包含相关的 CDK 构造或 Terraform 模块。
通用基础设施即代码项目的结构如下:
文件夹packages/common/constructs
文件夹src
文件夹app/ Constructs for infrastructure specific to a project/generator
- …
文件夹core/ Generic constructs which are reused by constructs in
app- …
- index.ts Entry point exporting constructs from
app
- project.json Project build targets and configuration
文件夹packages/common/terraform
文件夹src
文件夹app/ Terraform modules for infrastructure specific to a project/generator
- …
文件夹core/ Generic modules which are reused by modules in
app- …
- project.json Project build targets and configuration
您还将根据所选的 iac 找到以下生成的基础设施代码:
文件夹packages/common/constructs/src
文件夹core
- user-identity.ts Construct which defines the user pool and identity pool
文件夹packages/common/terraform/src
文件夹core
文件夹user-identity
- main.tf Module wrapper for the identity configuration
文件夹identity
- identity.tf Core identity infrastructure including Cognito User Pool and Identity Pool
文件夹add-callback-url
- add-callback-url.tf Module for adding callback URLs to existing user pool clients
此生成器在现有的静态网站架构中添加了 Amazon Cognito 用户池(用于登录)和身份池(用于将已登录用户联合到作用域 IAM 凭证):
用户池在 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(短信验证码或基于时间的一次性密码)。您可以将 MFA 设置为可选、完全关闭,或限制可用的第二因素方法:
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 独立启用或禁用每种第二因素方法;当 mfa 为 Mfa.OFF 时它们无效。将 mfa: Mfa.REQUIRED 设置为同时禁用两种方法会在合成时被拒绝,因为这样就没有人能够完成登录。
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 独立启用或禁用每种第二因素方法;当 mfa 为 "OFF" 时它们无效。
Web 应用程序防火墙 (WAF)
Section titled “Web 应用程序防火墙 (WAF)”默认情况下,用户池与 AWS WAFv2 Web ACL 关联,使用 AWSManagedRulesCommonRuleSet 和 AWSManagedRulesKnownBadInputsRuleSet 托管规则组。如果您希望管理自己的 Web ACL 或不需要,可以禁用此功能:
new UserIdentity(this, 'Identity', { enableWaf: false });module "user_identity" { source = "../../common/terraform/src/core/user-identity"
enable_waf = false}基础设施使用
Section titled “基础设施使用”您需要将用户身份基础设施添加到堆栈中,在网站_之前_声明它:
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 构造会自动添加必要的运行时配置,以确保您的网站可以指向正确的 Cognito 用户池进行身份验证。
您需要添加用户身份模块,并确保您的网站依赖于它:
# 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]}用户身份模块会自动添加必要的运行时配置,以确保您的网站可以指向正确的 Cognito 用户池进行身份验证。
授予已认证用户访问权限
Section titled “授予已认证用户访问权限”为了授予已认证用户执行某些操作的访问权限,例如授予调用 API 的权限,您可以向身份池已认证角色添加 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}/*" } ] })}