此技能帮助你构建、配置、调试和管理AWS Cognito资源——用户池、身份池、应用程序客户端、Lambda触发器、联合以及与其他AWS服务的集成。
快速决策:用户需要什么?
- 从零开始的新Cognito设置 → 阅读
references/setup-guide.md,然后按照设置工作流程进行
- CDK / CloudFormation / Terraform IaC → 阅读
references/iac-patterns.md获取生产就绪的模板
- 认证流程实现 → 阅读
references/auth-flows.md获取SDK代码和流程选择
- 调试/故障排除 → 阅读
references/troubleshooting.md获取常见问题和修复方法
- Lambda触发器 → 阅读
references/lambda-triggers.md获取触发器模式
- 安全加固 → 阅读
references/security.md获取最佳实践
在生成任何代码或配置之前,请阅读相关的参考文件。多个文件可能适用——例如,新的CDK设置将受益于setup-guide.md和iac-patterns.md。
核心概念(始终牢记)
用户池 vs 身份池
这是两个主要的Cognito组件,它们有不同的用途:
- 用户池:用户目录和OIDC身份提供商。处理注册、登录、MFA、令牌发放(ID令牌、访问令牌、刷新令牌)以及与外部IdP的联合。将其视为"这个用户是谁?"
- 身份池(联合身份):将令牌(来自用户池、社交提供商、SAML或OIDC)交换为临时AWS凭证(STS)。将其视为"此用户可以访问哪些AWS资源?"常见架构同时使用两者:用户池验证用户并发放令牌 → 身份池将这些令牌交换为AWS凭证 → 用户访问S3、DynamoDB等。
功能计划(定价层)
截至2024年底,Cognito使用功能计划而不是旧的"高级安全"开关:
- Lite:低成本,基本认证功能。适合MAU较少的简单应用。
- Essentials(新池的默认设置):所有最新认证功能,包括访问令牌自定义和托管登录。
- Plus:Essentials中的所有内容加上威胁保护(自适应认证、凭据泄露检测)。始终询问用户需要哪个计划,或为新设置默认使用Essentials。
令牌类型
- ID令牌:包含用户身份声明(email、name、groups、自定义属性)。用于后端身份验证。
- 访问令牌:包含范围和授权操作。用于API授权(例如API Gateway Cognito授权方)。
- 刷新令牌:长期令牌,用于在无需重新认证的情况下获取新的ID/访问令牌。默认有效期为30天。
工作流程:构建Cognito解决方案
步骤1:明确需求
在编写任何代码之前,确定:
- 认证方法:用户名/密码?仅邮箱?手机?社交登录(Google、Apple、Facebook)?企业SAML/OIDC?
- MFA:必需、可选还是关闭?短信、TOTP验证器应用还是邮箱?
- 自助注册:启用还是仅管理员创建用户?
- 令牌使用:仅前端(SPA/移动)?后端API授权?直接访问AWS资源?
- IaC偏好:CDK(TypeScript/Python)、CloudFormation、Terraform还是控制台/CLI?
- 前端框架:React/Amplify、Next.js、Vue、移动端(iOS/Android)还是自定义?
步骤2:设计架构
根据需求,确定:
- 用户池配置(登录别名、属性、密码策略、MFA)
- 应用程序客户端——公共(无密钥,用于SPA/移动)vs 机密(有密钥,用于服务端)
- OAuth流程——授权码(公共客户端使用PKCE)、隐式(遗留,避免)、客户端凭据(M2M)
- 是否需要身份池(仅在用户需要直接访问AWS资源时需要)
- 需要的Lambda触发器(预注册、预确认、预令牌生成、自定义认证等)
- 域名——Cognito托管前缀域名还是自定义域名
步骤3:实施
阅读适当的参考文件并生成代码。始终:
- 使用最新的CDK v2构造(
aws-cdk-lib/aws-cognito)——永远不要使用CDK v1
- 对于SDK代码,使用AWS SDK v3(
@aws-sdk/client-cognito-identity-provider)——永远不要使用v2
- 对于前端,首选Amplify v6(
aws-amplify)模式
- 包含适当的错误处理和令牌刷新逻辑
- 在生产环境中将
RemovalPolicy.RETAIN设置为用户池(防止数据丢失)
- 永远不要硬编码密钥——使用环境变量或AWS Secrets Manager
步骤4:安全审查
在声明完成之前,根据references/security.md进行验证:
- 生产环境启用MFA(至少可选)
- 密码策略满足要求(最少8个字符,复杂性规则)
- 令牌有效期合理
- 公共面向的认证端点考虑使用WAF
- 任何身份池角色使用最小权限IAM
- 机密客户端使用客户端密钥
- 仅使用HTTPS回调URL
常见模式快速参考
Cognito + API Gateway
在API Gateway上使用Cognito用户池授权方。访问令牌自动验证。令牌中的范围控制哪些API方法可访问。
Cognito + AppSync
在GraphQL API上配置AMAZON_COGNITO_USER_POOLS授权。在模式中使用@auth指令进行细粒度访问控制。
Cognito + S3(通过身份池)
用户池 → 身份池 → 具有S3权限的IAM角色,作用域为${cognito-identity.amazonaws.com:sub}/*,用于每个用户的文件夹。
Cognito + Lambda(自定义认证)
使用CUSTOM_AUTH流程和Define、Create和Verify Auth Challenge触发器进行无密码(魔法链接、OTP)或多步认证。
机器对机器(M2M)
使用具有资源服务器和自定义作用域的客户端凭据授权。无用户交互——一个应用向另一个应用进行认证。
重要提醒
- 创建时标记为必需的用户池属性以后无法更改。仔细规划属性。
- 自定义属性始终以
custom:为前缀(例如custom:company)。
sub属性是唯一、不可变的用户标识符。将其用作主键,而不是email或用户名。
- 邮箱/电话验证与登录别名分开。自动验证你用于登录的内容。
- Cognito有服务配额(例如API请求速率限制)。对于高流量应用,主动请求配额增加。
- Lambda触发器同步执行,有5秒超时。保持快速执行。
This skill helps you build, configure, debug, and manage AWS Cognito resources — user pools, identity pools, app clients, Lambda triggers, federation, and integrations with other AWS services.
Quick Decision: What Does the User Need?
- New Cognito setup from scratch → Read
references/setup-guide.md, then follow the setup workflow
- CDK / CloudFormation / Terraform IaC → Read
references/iac-patterns.md for production-ready templates
- Authentication flow implementation → Read
references/auth-flows.md for SDK code and flow selection
- Debugging / troubleshooting → Read
references/troubleshooting.md for common issues and fixes
- Lambda triggers → Read
references/lambda-triggers.md for trigger patterns
- Security hardening → Read
references/security.md for best practices
Read the relevant reference file(s) before generating any code or configuration. Multiple files may apply — for example, a new CDK setup would benefit from both setup-guide.md and iac-patterns.md.
Core Concepts (Always Keep in Mind)
User Pools vs Identity Pools
These are the two main Cognito components and they serve different purposes:
- User Pool: A user directory and OIDC identity provider. Handles sign-up, sign-in, MFA, token issuance (ID token, access token, refresh token), and federation with external IdPs. Think of it as "who is this user?"
- Identity Pool (Federated Identities): Exchanges tokens (from a user pool, social provider, SAML, or OIDC) for temporary AWS credentials (STS). Think of it as "what AWS resources can this user access?"
A common architecture uses both: User Pool authenticates the user and issues tokens → Identity Pool exchanges those tokens for AWS credentials → User accesses S3, DynamoDB, etc.
Feature Plans (Pricing Tiers)
As of late 2024, Cognito uses feature plans instead of the old "advanced security" toggle:
- Lite: Low-cost, basic auth features. Good for simple apps with fewer MAUs.
- Essentials (default for new pools): All latest auth features including access-token customization and managed login.
- Plus: Everything in Essentials plus threat protection (adaptive auth, compromised credential detection).
Always ask the user which plan they need, or default to Essentials for new setups.
Token Types
- ID Token: Contains user identity claims (email, name, groups, custom attributes). Use for identity verification on your backend.
- Access Token: Contains scopes and authorized actions. Use for API authorization (e.g., API Gateway Cognito Authorizer).
- Refresh Token: Long-lived token to obtain new ID/access tokens without re-authentication. Default validity is 30 days.
Workflow: Building a Cognito Solution
Step 1: Clarify Requirements
Before writing any code, determine:
- Auth methods: Username/password? Email-only? Phone? Social login (Google, Apple, Facebook)? Enterprise SAML/OIDC?
- MFA: Required, optional, or off? SMS, TOTP authenticator app, or email?
- Self-service sign-up: Enabled or admin-only user creation?
- Token usage: Frontend-only (SPA/mobile)? Backend API authorization? Direct AWS resource access?
- IaC preference: CDK (TypeScript/Python), CloudFormation, Terraform, or console/CLI?
- Frontend framework: React/Amplify, Next.js, Vue, mobile (iOS/Android), or custom?
Step 2: Design the Architecture
Based on requirements, determine:
- User Pool configuration (sign-in aliases, attributes, password policy, MFA)
- App client(s) — public (no secret, for SPAs/mobile) vs confidential (with secret, for server-side)
- OAuth flows — Authorization Code (with PKCE for public clients), Implicit (legacy, avoid), Client Credentials (M2M)
- Whether an Identity Pool is needed (only if users need direct AWS resource access)
- Lambda triggers needed (pre-sign-up, post-confirmation, pre-token-generation, custom auth, etc.)
- Domain — Cognito-hosted prefix domain or custom domain
Step 3: Implement
Read the appropriate reference files and generate code. Always:
- Use the latest CDK v2 constructs (
aws-cdk-lib/aws-cognito) — never CDK v1
- For SDK code, use AWS SDK v3 (
@aws-sdk/client-cognito-identity-provider) — never v2
- For frontend, prefer Amplify v6 (
aws-amplify) patterns
- Include proper error handling and token refresh logic
- Set
RemovalPolicy.RETAIN on user pools in production (data loss prevention)
- Never hardcode secrets — use environment variables or AWS Secrets Manager
Step 4: Security Review
Before declaring done, verify against references/security.md:
- MFA is enabled (at least optional) for production
- Password policy meets requirements (minimum 8 chars, complexity rules)
- Token validity periods are reasonable
- WAF is considered for public-facing auth endpoints
- Least-privilege IAM for any Identity Pool roles
- Client secrets are used for confidential clients
- HTTPS-only callback URLs
Common Patterns Quick Reference
Cognito + API Gateway
Use a Cognito User Pool Authorizer on API Gateway. The access token is validated automatically. Scopes in the token control which API methods are accessible.
Cognito + AppSync
Configure
AMAZON_COGNITO_USER_POOLS authorization on your GraphQL API. Use
@auth directives in your schema for fine-grained access control.
Cognito + S3 (via Identity Pool)
User Pool → Identity Pool → IAM role with S3 permissions scoped to
${cognito-identity.amazonaws.com:sub}/* for per-user folders.
Cognito + Lambda (Custom Auth)
Use
CUSTOM_AUTH flow with Define, Create, and Verify Auth Challenge triggers for passwordless (magic link, OTP) or multi-step authentication.
Machine-to-Machine (M2M)
Use Client Credentials grant with a resource server and custom scopes. No user interaction — one app authenticating to another.
Important Reminders
- User pool attributes marked as required at creation CANNOT be changed later. Plan attributes carefully.
- Custom attributes are always prefixed with
custom: (e.g., custom:company).
- The
sub attribute is the unique, immutable user identifier. Use it as your primary key, not email or username.
- Email/phone verification is separate from sign-in aliases. Auto-verify what you use for sign-in.
- Cognito has service quotas (e.g., API request rate limits). For high-volume apps, request quota increases proactively.
- Lambda triggers execute synchronously and have a 5-second timeout. Keep them fast.