islamelkadi/terraform-aws-cognito
GitHub: islamelkadi/terraform-aws-cognito
一个符合 CIS、NIST、PCI DSS 等安全合规标准的生产级 AWS Cognito 身份认证 Terraform 模块,提供完整的 OAuth 2.0/OIDC 认证基础设施配置。
Stars: 0 | Forks: 0
# Terraform AWS Cognito Authentication Module
[](https://github.com/islamelkadi/terraform-aws-cognito/actions/workflows/terraform-security.yaml)
[](https://github.com/islamelkadi/terraform-aws-cognito/actions/workflows/terraform-lint.yaml)
[](https://github.com/islamelkadi/terraform-aws-cognito/actions/workflows/terraform-docs.yaml)
全面的 Terraform 模块,用于构建 AWS Cognito 身份验证基础设施,遵循安全最佳实践、CIS Benchmark 合规性,并提供生产级配置。
## 概述
本模块提供完整的 Cognito 身份验证解决方案,包含四个协同工作的子模块,用于构建安全、可扩展的身份验证系统:
1. **User Pool** - 核心身份验证功能,包括密码策略、MFA 和用户管理
2. **User Pool Client** - OAuth 2.0/OIDC 应用程序集成
3. **User Pool Domain** - 托管 UI,支持自定义或 Cognito 管理的域名
4. **Identity Pool** - 联合身份和 AWS 凭证管理
## 目录
- [前置条件](#prerequisites)
- [安全](#security)
- [功能](#features)
- [使用](#usage)
- [要求](#requirements)
- [MCP Servers](#mcp-servers)
## 前置条件
本模块专为 macOS 设计。您的机器上必须已安装以下软件:
- Python 3 和 pip
- [Kiro](https://kiro.dev) 和 Kiro CLI
- [Homebrew](https://brew.sh)
要安装其余开发工具,请运行:
```
make bootstrap
```
这将安装/升级:tfenv、Terraform (通过 tfenv)、tflint、terraform-docs、checkov 和 pre-commit。
## 安全
### 安全控制
本模块实施安全控制以符合以下标准:
- AWS Foundational Security Best Practices (FSBP)
- CIS AWS Foundations Benchmark
- NIST 800-53 Rev 5
- NIST 800-171 Rev 2
- PCI DSS v4.0
### 已实施的控制
- [x] **密码策略**:符合 CIS 标准(14 位以上字符,复杂性要求)
- [x] **多因素认证 (MFA)**:基于 TOTP 的 MFA 支持
- [x] **高级安全**:威胁检测和基于风险的认证
- [x] **删除保护**:防止意外删除用户池
- [x] **Token 安全**:可配置的 token 有效期和撤销
- [x] **加密**:静态和传输中的数据加密
- [x] **账户恢复**:基于电子邮件和电话的恢复机制
- [x] **安全控制覆盖**:可扩展的覆盖系统,附带审计说明
### 安全最佳实践
**生产环境 User Pools:**
- 启用 MFA(至少 OPTIONAL 模式)
- 使用符合 CIS 标准的密码策略(14 位以上字符)
- 启用高级安全模式 (ENFORCED)
- 启用删除保护
- 配置账户恢复机制
- 使用自定义域名以获得更好的品牌形象和安全性
**开发环境 User Pools:**
- 可接受宽松的密码策略,但需说明理由
- MFA 可选,用于测试
- 可禁用删除保护
有关完整的安全标准和实施细节,请参阅 [AWS Security Standards](../../../.kiro/steering/aws/aws-security-standards.md)。
### 基于环境的安全控制
安全控制通过 [terraform-aws-metadata](https://github.com/islamelkadi/terraform-aws-metadata?tab=readme-ov-file#security-profiles) 模块的安全配置文件根据环境自动应用:
| Control | Dev | Staging | Prod |
|---------|-----|---------|------|
| Password policy (CIS) | Relaxed | CIS-compliant (14+ chars) | CIS-compliant (14+ chars) |
| MFA | OFF | OPTIONAL | OPTIONAL/ON |
| Advanced security mode | AUDIT | ENFORCED | ENFORCED |
| Deletion protection | Disabled | Enabled | Enabled |
| Token revocation | Optional | Enabled | Enabled |
有关安全配置文件以及控制如何随环境变化的完整详细信息,请参阅 [Security Profiles](https://github.com/islamelkadi/terraform-aws-metadata?tab=readme-ov-file#security-profiles) 文档。
### 安全扫描抑制
本模块抑制了某些 Checkov 安全检查,这些检查要么不适用于示例/演示代码,要么代表可选功能。以下检查在 `.checkov.yaml` 中被抑制:
**模块源版本控制 (CKV_TF_1, CKV_TF_2)**
- 被抑制是因为我们使用语义版本标签 (`?ref=v1.0.0`) 而非提交哈希,以提高可维护性和可读性
- 语义版本控制是稳定版本的有效且广泛接受的版本控制策略
**Cognito 可选功能**
- **未认证访问 (CKV_AWS_366)**:未认证的访客访问取决于具体用例;某些应用程序需要公开访问;如果不需要,用户应禁用此功能
## 功能
- **符合 CIS Benchmark**:密码策略和安全控制符合 CIS AWS Foundations Benchmark
- **OAuth 2.0 & OpenID Connect**:全面支持现代身份验证流程
- **多因素认证 (MFA)**:基于 TOTP 的 MFA,可选择强制执行
- **托管 UI**:可自定义的登录/注册页面,支持自定义域名
- **联合身份**:集成社交提供商和 SAML
- **AWS 凭证管理**:为已认证用户提供临时 AWS 凭证
- **默认安全**:加密、删除保护和高级威胁检测
- **灵活配置**:针对所有用例的广泛自定义选项
- **安全控制覆盖**:用于开发/测试的文档化覆盖系统
## 架构
```
┌────────────────────────────────────────────────────────────┐
│ Cognito User Pool │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ Password Policy (CIS Compliant) │ │
│ │ - Min 14 chars, complexity requirements │ │
│ │ - MFA (TOTP) │ │
│ │ - Email/Phone verification │ │
│ │ - Account recovery │ │
│ │ - Lambda triggers │ │
│ │ - Advanced security (threat detection) │ │
│ └──────────────────────────────────────────────────────┘ │
└────────────────────────────────────────────────────────────┘
│
├─────────────────────────────────┐
│ │
▼ ▼
┌─────────────────────────────────────┐ ┌──────────────────────────────┐
│ User Pool Client │ │ User Pool Domain │
│ ┌───────────────────────────────┐ │ │ ┌────────────────────────┐ │
│ │ OAuth 2.0 Flows │ │ │ │ Hosted UI │ │
│ │ - Authorization Code │ │ │ │ - Custom Domain │ │
│ │ - Implicit (legacy) │ │ │ │ - Cognito Domain │ │
│ │ - Client Credentials (M2M) │ │ │ │ - CloudFront │ │
│ │ │ │ │ │ - ACM Certificate │ │
│ │ Token Management │ │ │ └────────────────────────┘ │
│ │ - Access, ID, Refresh tokens │ │ └──────────────────────────────┘
│ │ - Configurable validity │ │
│ │ - Token revocation │ │
│ └───────────────────────────────┘ │
└─────────────────────────────────────┘
│
▼
┌────────────────────────────────────────────────────────────┐
│ Identity Pool │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ Federated Identity │ │
│ │ - Cognito User Pool │ │
│ │ - Social Providers (Google, Facebook, Amazon) │ │
│ │ - SAML │ │
│ │ - OpenID Connect │ │
│ │ │ │
│ │ IAM Role Mappings │ │
│ │ - Authenticated users → IAM role │ │
│ │ - Unauthenticated users → IAM role (optional) │ │
│ │ - Advanced role mapping rules │ │
│ │ │ │
│ │ AWS Credentials │ │
│ │ - Temporary credentials for AWS API access │ │
│ └──────────────────────────────────────────────────────┘ │
└────────────────────────────────────────────────────────────┘
```
## 快速开始
### 基本身份验证设置
```
# 1. 创建 User Pool
module "user_pool" {
source = "github.com/islamelkadi/terraform-aws-cognito"
namespace = "example"
environment = "prod"
name = "corporate-actions"
region = "us-east-1"
# CIS-compliant password policy (default)
password_policy = {
minimum_length = 14
require_lowercase = true
require_uppercase = true
require_numbers = true
require_symbols = true
temporary_password_validity_days = 7
}
# Optional MFA
mfa_configuration = "OPTIONAL"
tags = {
Project = "CorporateActions"
}
}
# 2. 创建 User Pool Client
module "user_pool_client" {
source = "github.com/islamelkadi/terraform-aws-cognito"
namespace = "example"
environment = "prod"
name = "web-app"
region = "us-east-1"
user_pool_id = module.user_pool.user_pool_id
# OAuth configuration
oauth_flows = ["code"]
oauth_scopes = ["openid", "email", "profile"]
callback_urls = ["https://app.example.com/callback"]
logout_urls = ["https://app.example.com/logout"]
}
# 3. 创建 User Pool Domain (可选 - 用于 Hosted UI)
module "user_pool_domain" {
source = "github.com/islamelkadi/terraform-aws-cognito"
namespace = "example"
environment = "prod"
name = "corporate-actions"
user_pool_id = module.user_pool.user_pool_id
domain_prefix = "example-corp-actions"
tags = {
Project = "CorporateActions"
}
}
# 4. 创建 Identity Pool (可选 - 用于 AWS credentials)
module "identity_pool" {
source = "github.com/islamelkadi/terraform-aws-cognito"
namespace = "example"
environment = "prod"
name = "corporate-actions"
region = "us-east-1"
cognito_identity_providers = [
{
client_id = module.user_pool_client.client_id
provider_name = "cognito-idp.ca-central-1.amazonaws.com/${module.user_pool.user_pool_id}"
}
]
authenticated_role_policy_arns = {
dynamodb = aws_iam_policy.dynamodb_access.arn
s3 = aws_iam_policy.s3_access.arn
}
tags = {
Project = "CorporateActions"
}
}
```
## 模块文档
每个子模块都有详尽的文档:
- [User Pool](modules/user-pool/README.md) - 核心身份验证配置
- [User Pool Client](modules/user-pool-client/README.md) - OAuth 2.0 应用程序集成
- [User Pool Domain](modules/user-pool-domain/README.md) - 托管 UI 和自定义域名
- [Identity Pool](modules/identity-pool/README.md) - 联合身份和 AWS 凭证
## 常见用例
### 1. 带托管 UI 的 Web 应用程序
```
# 启用 MFA 的 User Pool
module "user_pool" {
source = "github.com/islamelkadi/terraform-aws-cognito"
mfa_configuration = "ON"
}
# Web App Client
module "web_client" {
source = "github.com/islamelkadi/terraform-aws-cognito"
oauth_flows = ["code"]
generate_secret = false # Public client (SPA)
}
# 用于 Hosted UI 的 Custom Domain
module "domain" {
source = "github.com/islamelkadi/terraform-aws-cognito"
use_custom_domain = true
custom_domain = "auth.example.com"
certificate_arn = aws_acm_certificate.auth.arn
}
```
### 2. 带机器对机器身份验证的 API
```
# User Pool
module "user_pool" {
source = "github.com/islamelkadi/terraform-aws-cognito"
}
# M2M Client
module "m2m_client" {
source = "github.com/islamelkadi/terraform-aws-cognito"
generate_secret = true
oauth_flows = ["client_credentials"]
oauth_scopes = ["aws.cognito.signin.user.admin"]
}
```
### 3. 带社交登录的移动应用
```
# User Pool
module "user_pool" {
source = "github.com/islamelkadi/terraform-aws-cognito"
}
# Mobile App Client
module "mobile_client" {
source = "github.com/islamelkadi/terraform-aws-cognito"
oauth_flows = ["code"]
explicit_auth_flows = [
"ALLOW_USER_SRP_AUTH",
"ALLOW_REFRESH_TOKEN_AUTH"
]
}
# 包含 Social Providers 的 Identity Pool
module "identity_pool" {
source = "github.com/islamelkadi/terraform-aws-cognito"
supported_login_providers = {
"accounts.google.com" = var.google_client_id
"graph.facebook.com" = var.facebook_app_id
}
}
```
### 4. 演示环境(简化安全性)
```
# 用于 Demo 的宽松安全策略 User Pool
module "demo_user_pool" {
source = "github.com/islamelkadi/terraform-aws-cognito"
password_policy = {
minimum_length = 8
require_lowercase = true
require_uppercase = false
require_numbers = true
require_symbols = false
temporary_password_validity_days = 7
}
mfa_configuration = "OFF"
advanced_security_mode = "AUDIT"
enable_deletion_protection = false
security_control_overrides = {
disable_deletion_protection = true
disable_mfa_requirement = true
disable_password_complexity = true
justification = "Demo environment for stakeholder presentation"
}
}
```
## 与 API Gateway 集成
### Cognito Authorizer
```
# 创建 API Gateway
resource "aws_api_gateway_rest_api" "api" {
name = "corporate-actions-api"
}
# 创建 Cognito Authorizer
resource "aws_api_gateway_authorizer" "cognito" {
name = "cognito-authorizer"
rest_api_id = aws_api_gateway_rest_api.api.id
type = "COGNITO_USER_POOLS"
provider_arns = [module.user_pool.user_pool_arn]
}
# 保护 API Method
resource "aws_api_gateway_method" "protected" {
rest_api_id = aws_api_gateway_rest_api.api.id
resource_id = aws_api_gateway_resource.resource.id
http_method = "GET"
authorization = "COGNITO_USER_POOLS"
authorizer_id = aws_api_gateway_authorizer.cognito.id
}
```
### Lambda 函数集成
```
# Lambda function 可以从 event 中访问用户身份
def lambda_handler(event, context):
# Get user identity from Cognito authorizer
claims = event['requestContext']['authorizer']['claims']
user_id = claims['sub']
email = claims['email']
# Your business logic here
return {
'statusCode': 200,
'body': json.dumps({'message': f'Hello {email}'})
}
```
## OAuth 2.0 流程
### 授权码流程 (推荐)
最安全的 Web 和移动应用程序流程。
```
module "client" {
source = "github.com/islamelkadi/terraform-aws-cognito"
oauth_flows = ["code"]
generate_secret = true # For server-side apps
callback_urls = ["https://app.example.com/callback"]
logout_urls = ["https://app.example.com/logout"]
}
```
**流程:**
1. 用户点击 "Login" → 重定向到 Cognito Hosted UI
2. 用户进行身份验证 → Cognito 返回授权码
3. 应用程序用授权码换取 token(access、ID、refresh)
4. 应用程序使用 access token 调用 API
### 隐式流程 (旧版 - 不推荐)
SPA 的旧版流程。请改用带 PKCE 的授权码流程。
```
module "client" {
source = "github.com/islamelkadi/terraform-aws-cognito"
oauth_flows = ["implicit"]
generate_secret = false
}
```
### 客户端凭证流程 (M2M)
用于无用户上下文的机器对机器身份验证。
```
module "client" {
source = "github.com/islamelkadi/terraform-aws-cognito"
oauth_flows = ["client_credentials"]
generate_secret = true
oauth_scopes = ["aws.cognito.signin.user.admin"]
}
```
**流程:**
1. 服务使用 client ID 和 secret 进行身份验证
2. Cognito 返回 access token
3. 服务使用 access token 调用 API
## MFA 设置和最佳实践
### 启用 MFA
```
module "user_pool" {
source = "github.com/islamelkadi/terraform-aws-cognito"
# MFA options: OFF, OPTIONAL, ON
mfa_configuration = "OPTIONAL" # Users can enable MFA
# mfa_configuration = "ON" # MFA required for all users
}
```
### MFA 配置选项
1. **OFF**:不支持 MFA
2. **OPTIONAL**:用户可以启用 MFA(推荐大多数应用程序使用)
3. **ON**:所有用户必须使用 MFA(最高安全性)
### TOTP (基于时间的一次性密码)
Cognito 支持使用验证器应用的基于 TOTP 的 MFA:
- Google Authenticator
- Microsoft Authenticator
- Authy
- 1Password
### MFA 最佳实践
1. **从 OPTIONAL 开始**:允许用户选择加入 MFA
2. **教育用户**:提供清晰的 MFA 设置说明
3. **恢复机制**:为丢失 MFA 设备的用户配置账户恢复
4. **对管理员强制执行**:要求管理员账户使用 MFA
5. **监控采用率**:追踪 MFA 注册率
### MFA 用户体验
```
1. User signs up → Account created
2. User logs in → Prompted to set up MFA (if OPTIONAL)
3. User scans QR code with authenticator app
4. User enters verification code → MFA enabled
5. Future logins → Username/password + MFA code
```
## 安全注意事项
### 密码策略 (CIS Benchmark)
默认密码策略符合 CIS AWS Foundations Benchmark:
```
password_policy = {
minimum_length = 14 # CIS requirement
require_lowercase = true
require_uppercase = true
require_numbers = true
require_symbols = true
temporary_password_validity_days = 7
}
```
### 高级安全功能
```
module "user_pool" {
source = "github.com/islamelkadi/terraform-aws-cognito"
# Threat detection and risk-based authentication
advanced_security_mode = "ENFORCED" # AUDIT or ENFORCED
# Prevent user enumeration attacks
# (in user pool client)
}
```
### 删除保护
```
module "user_pool" {
source = "github.com/islamelkadi/terraform-aws-cognito"
# Prevent accidental deletion
enable_deletion_protection = true # Recommended for production
}
```
### Token 安全
```
module "user_pool_client" {
source = "github.com/islamelkadi/terraform-aws-cognito"
# Enable token revocation
enable_token_revocation = true
# Shorter token validity for public clients
token_validity = {
refresh_token_validity = 7 # 7 days
access_token_validity = 30 # 30 minutes
id_token_validity = 30 # 30 minutes
refresh_token_unit = "days"
access_token_unit = "minutes"
id_token_unit = "minutes"
}
}
```
### 安全控制覆盖
当您需要禁用安全控制时(例如用于开发),请提供说明理由:
```
security_control_overrides = {
disable_deletion_protection = true
disable_mfa_requirement = true
justification = "Development environment for testing"
}
```
## 最佳实践
### 1. User Pool 配置
- ✅ 启用 MFA(至少 OPTIONAL)
- ✅ 使用符合 CIS 标准的密码策略(14 位以上字符,复杂性)
- ✅ 启用高级安全模式(生产环境使用 ENFORCED)
- ✅ 为生产环境启用删除保护
- ✅ 配置账户恢复机制
- ✅ 使用 SES 发送电子邮件(更好的送达率)
### 2. User Pool Client 配置
- ✅ 使用授权码流程(最安全)
- ✅ 启用 token 撤销
- ✅ 所有回调/注销 URL 使用 HTTPS
- ✅ 限制 token 有效期(越短越安全)
- ✅ 仅对服务器端应用生成客户端密钥
- ✅ 将 OAuth scope 限制为必要的权限
### 3. User Pool Domain 配置
- ✅ 生产环境使用自定义域名(更好的品牌形象)
- ✅ 确保 ACM 证书位于 us-east-1 区域
- ✅ 为自定义域名配置 Route53 别名记录
- ✅ 仅使用 HTTPS
### 4. Identity Pool 配置
- ✅ 默认禁用未认证访问
- ✅ 使用最小权限 IAM 策略
- ✅ 使用高级角色映射进行细粒度访问控制
- ✅ 监控 IAM 角色使用情况
### 5. Lambda Triggers
- ✅ 使用 Lambda triggers 进行自定义工作流
- ✅ 实现适当的错误处理
- ✅ 保持触发函数快速(< 5 秒)
- ✅ 记录所有触发器执行日志
### 6. 监控和日志
- ✅ 为 Lambda triggers 启用 CloudWatch Logs
- ✅ 监控身份验证指标
- ✅ 为失败的登录尝试设置告警
- ✅ 追踪 MFA 注册率
## 故障排除
### 常见问题
#### 1. 自定义域名无法工作
**症状**:自定义域名返回 404 或 SSL 错误
**解决方案**:
- 验证 ACM 证书位于 `us-east-1` 区域
- 验证证书处于 `ISSUED` 状态
- 等待最多 60 分钟以完成 CloudFront distribution 部署
- 验证 Route53 别名记录指向 CloudFront distribution
#### 2. OAuth 回调错误
**症状**:"redirect_uri_mismatch" 错误
**解决方案**:
- 验证回调 URL 在客户端的 `callback_urls` 列表中
- 确保 URL 完全匹配(包括协议、域名、路径)
- 检查尾部斜杠
#### 3. Token 验证失败
**症状**:API Gateway 中出现 "Invalid token" 错误
**解决方案**:
- 验证 token 未过期
- 验证 token 来自正确的用户池
- 检查 API Gateway authorizer 配置
- 验证用户池 ARN 正确
#### 4. MFA 设置问题
**症状**:用户无法设置 MFA
**解决方案**:
- 验证 `mfa_configuration` 设置为 `OPTIONAL` 或 `ON`
- 检查用户是否已验证电子邮件或电话号码
- 验证验证器应用与正确的时间同步
## 示例
每个模块都包含一个完整的示例:
- [User Pool 示例](modules/user-pool/example/)
- [User Pool Client 示例](modules/user-pool-client/example/)
- [User Pool Domain 示例](modules/user-pool-domain/example/)
- [Identity Pool 示例](modules/identity-pool/example/)
## 要求
| Name | Version |
|------|---------|
| terraform | >= 1.14.3 |
| aws | >= 6.34 |
## 参考资料
- [AWS Cognito Documentation](https://docs.aws.amazon.com/cognito/)
- [OAuth 2.0 Specification](https://oauth.net/2/)
- [OpenID Connect Specification](https://openid.net/connect/)
- [CIS AWS Foundations Benchmark](https://www.cisecurity.org/benchmark/amazon_web_services)
- [OWASP Authentication Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html)
## MCP Servers
本模块包含两个在 `.kiro/settings/mcp.json` 中配置的 [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) 服务器,用于iro:
| Server | Package | Description |
|--------|---------|-------------|
| `aws-docs` | `awslabs.aws-documentation-mcp-server@latest` | 提供 AWS 文档访问,用于服务功能、API 参考和最佳实践的上下文查找。 |
| `terraform` | `awslabs.terraform-mcp-server@latest` | 支持直接从 IDE 执行 Terraform 操作(init、validate、plan、fmt、tflint),并为常见工作流提供自动批准的命令。 |
两个服务器均通过 `uvx` 运行,除了 [bootstrap](#prerequisites) 步骤外,无需额外安装。
## Requirements
No requirements.
## Providers
No providers.
## Modules
No modules.
## Resources
No resources.
## Inputs
No inputs.
## Outputs
No outputs.
## 许可证
MIT Licensed. 详见 [LICENSE](LICENSE)。
标签:Amazon Cognito, ATTACK-Python-Client, AWS, CIS Benchmark, Cognito, DPI, ECS, IAM, MFA, OAuth 2.0, OIDC, SSO, Streamlit, Terraform, Terraform Module, 企业级, 前端部署, 单点登录, 多因素认证, 安全合规, 密码策略, 无服务器, 生产就绪, 用户池, 网络代理, 联合身份验证, 访问控制, 身份池, 逆向工具, 速率限制