cognito
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAWS Cognito
AWS Cognito
Amazon Cognito provides authentication, authorization, and user management for web and mobile applications. Users can sign in directly or through federated identity providers.
Amazon Cognito为Web和移动应用提供认证、授权和用户管理功能。用户可以直接登录,也可以通过联合身份提供商登录。
Table of Contents
目录
Core Concepts
核心概念
User Pools
用户池
User directory for sign-up and sign-in. Provides:
- User registration and authentication
- OAuth 2.0 / OpenID Connect tokens
- MFA and password policies
- Customizable UI and flows
用于注册和登录的用户目录。提供以下功能:
- 用户注册与认证
- OAuth 2.0 / OpenID Connect令牌
- 多因素认证(MFA)与密码策略
- 可自定义的UI与流程
Identity Pools (Federated Identities)
身份池(联合身份)
Provide temporary AWS credentials to access AWS services. Users can be:
- Cognito User Pool users
- Social identity (Google, Facebook, Apple)
- SAML/OIDC enterprise identity
- Anonymous guests
为用户提供临时AWS凭证以访问AWS服务。支持的用户类型包括:
- Cognito用户池用户
- 社交身份(Google、Facebook、Apple)
- SAML/OIDC企业身份
- 匿名访客
Tokens
令牌
| Token | Purpose | Lifetime |
|---|---|---|
| ID Token | User identity claims | 1 hour |
| Access Token | API authorization | 1 hour |
| Refresh Token | Get new ID/Access tokens | 30 days (configurable) |
| 令牌类型 | 用途 | 有效期 |
|---|---|---|
| ID Token | 用户身份声明 | 1小时 |
| Access Token | API授权 | 1小时 |
| Refresh Token | 获取新的ID/Access令牌 | 30天(可配置) |
Common Patterns
常见模式
Create User Pool
创建用户池
AWS CLI:
bash
aws cognito-idp create-user-pool \
--pool-name my-app-users \
--policies '{
"PasswordPolicy": {
"MinimumLength": 12,
"RequireUppercase": true,
"RequireLowercase": true,
"RequireNumbers": true,
"RequireSymbols": true
}
}' \
--auto-verified-attributes email \
--username-attributes email \
--mfa-configuration OPTIONAL \
--user-attribute-update-settings '{
"AttributesRequireVerificationBeforeUpdate": ["email"]
}'AWS CLI:
bash
aws cognito-idp create-user-pool \
--pool-name my-app-users \
--policies '{
"PasswordPolicy": {
"MinimumLength": 12,
"RequireUppercase": true,
"RequireLowercase": true,
"RequireNumbers": true,
"RequireSymbols": true
}
}' \
--auto-verified-attributes email \
--username-attributes email \
--mfa-configuration OPTIONAL \
--user-attribute-update-settings '{
"AttributesRequireVerificationBeforeUpdate": ["email"]
}'Create App Client
创建应用客户端
bash
aws cognito-idp create-user-pool-client \
--user-pool-id us-east-1_abc123 \
--client-name my-web-app \
--generate-secret \
--explicit-auth-flows ALLOW_USER_SRP_AUTH ALLOW_REFRESH_TOKEN_AUTH \
--supported-identity-providers COGNITO \
--callback-urls https://myapp.com/callback \
--logout-urls https://myapp.com/logout \
--allowed-o-auth-flows code \
--allowed-o-auth-scopes openid email profile \
--allowed-o-auth-flows-user-pool-client \
--access-token-validity 60 \
--id-token-validity 60 \
--refresh-token-validity 30 \
--token-validity-units '{
"AccessToken": "minutes",
"IdToken": "minutes",
"RefreshToken": "days"
}'bash
aws cognito-idp create-user-pool-client \
--user-pool-id us-east-1_abc123 \
--client-name my-web-app \
--generate-secret \
--explicit-auth-flows ALLOW_USER_SRP_AUTH ALLOW_REFRESH_TOKEN_AUTH \
--supported-identity-providers COGNITO \
--callback-urls https://myapp.com/callback \
--logout-urls https://myapp.com/logout \
--allowed-o-auth-flows code \
--allowed-o-auth-scopes openid email profile \
--allowed-o-auth-flows-user-pool-client \
--access-token-validity 60 \
--id-token-validity 60 \
--refresh-token-validity 30 \
--token-validity-units '{
"AccessToken": "minutes",
"IdToken": "minutes",
"RefreshToken": "days"
}'Sign Up User
用户注册
python
import boto3
import hmac
import hashlib
import base64
cognito = boto3.client('cognito-idp')
def get_secret_hash(username, client_id, client_secret):
message = username + client_id
dig = hmac.new(
client_secret.encode('utf-8'),
message.encode('utf-8'),
digestmod=hashlib.sha256
).digest()
return base64.b64encode(dig).decode()
response = cognito.sign_up(
ClientId='client-id',
SecretHash=get_secret_hash('user@example.com', 'client-id', 'client-secret'),
Username='user@example.com',
Password='SecurePassword123!',
UserAttributes=[
{'Name': 'email', 'Value': 'user@example.com'},
{'Name': 'name', 'Value': 'John Doe'}
]
)python
import boto3
import hmac
import hashlib
import base64
cognito = boto3.client('cognito-idp')
def get_secret_hash(username, client_id, client_secret):
message = username + client_id
dig = hmac.new(
client_secret.encode('utf-8'),
message.encode('utf-8'),
digestmod=hashlib.sha256
).digest()
return base64.b64encode(dig).decode()
response = cognito.sign_up(
ClientId='client-id',
SecretHash=get_secret_hash('user@example.com', 'client-id', 'client-secret'),
Username='user@example.com',
Password='SecurePassword123!',
UserAttributes=[
{'Name': 'email', 'Value': 'user@example.com'},
{'Name': 'name', 'Value': 'John Doe'}
]
)Confirm Sign Up
确认注册
python
cognito.confirm_sign_up(
ClientId='client-id',
SecretHash=get_secret_hash('user@example.com', 'client-id', 'client-secret'),
Username='user@example.com',
ConfirmationCode='123456'
)python
cognito.confirm_sign_up(
ClientId='client-id',
SecretHash=get_secret_hash('user@example.com', 'client-id', 'client-secret'),
Username='user@example.com',
ConfirmationCode='123456'
)Authenticate User
用户认证
python
response = cognito.initiate_auth(
ClientId='client-id',
AuthFlow='USER_SRP_AUTH',
AuthParameters={
'USERNAME': 'user@example.com',
'SECRET_HASH': get_secret_hash('user@example.com', 'client-id', 'client-secret'),
'SRP_A': srp_a # From SRP library
}
)python
response = cognito.initiate_auth(
ClientId='client-id',
AuthFlow='USER_SRP_AUTH',
AuthParameters={
'USERNAME': 'user@example.com',
'SECRET_HASH': get_secret_hash('user@example.com', 'client-id', 'client-secret'),
'SRP_A': srp_a # From SRP library
}
)For simple password auth (not recommended for production)
简单密码认证(不推荐用于生产环境)
response = cognito.admin_initiate_auth(
UserPoolId='us-east-1_abc123',
ClientId='client-id',
AuthFlow='ADMIN_USER_PASSWORD_AUTH',
AuthParameters={
'USERNAME': 'user@example.com',
'PASSWORD': 'password',
'SECRET_HASH': get_secret_hash('user@example.com', 'client-id', 'client-secret')
}
)
tokens = response['AuthenticationResult']
id_token = tokens['IdToken']
access_token = tokens['AccessToken']
refresh_token = tokens['RefreshToken']
undefinedresponse = cognito.admin_initiate_auth(
UserPoolId='us-east-1_abc123',
ClientId='client-id',
AuthFlow='ADMIN_USER_PASSWORD_AUTH',
AuthParameters={
'USERNAME': 'user@example.com',
'PASSWORD': 'password',
'SECRET_HASH': get_secret_hash('user@example.com', 'client-id', 'client-secret')
}
)
tokens = response['AuthenticationResult']
id_token = tokens['IdToken']
access_token = tokens['AccessToken']
refresh_token = tokens['RefreshToken']
undefinedRefresh Tokens
刷新令牌
python
response = cognito.initiate_auth(
ClientId='client-id',
AuthFlow='REFRESH_TOKEN_AUTH',
AuthParameters={
'REFRESH_TOKEN': refresh_token,
'SECRET_HASH': get_secret_hash('user@example.com', 'client-id', 'client-secret')
}
)python
response = cognito.initiate_auth(
ClientId='client-id',
AuthFlow='REFRESH_TOKEN_AUTH',
AuthParameters={
'REFRESH_TOKEN': refresh_token,
'SECRET_HASH': get_secret_hash('user@example.com', 'client-id', 'client-secret')
}
)Create Identity Pool
创建身份池
bash
aws cognito-identity create-identity-pool \
--identity-pool-name my-app-identities \
--allow-unauthenticated-identities \
--cognito-identity-providers \
ProviderName=cognito-idp.us-east-1.amazonaws.com/us-east-1_abc123,\
ClientId=client-id,\
ServerSideTokenCheck=truebash
aws cognito-identity create-identity-pool \
--identity-pool-name my-app-identities \
--allow-unauthenticated-identities \
--cognito-identity-providers \
ProviderName=cognito-idp.us-east-1.amazonaws.com/us-east-1_abc123,\
ClientId=client-id,\
ServerSideTokenCheck=trueGet AWS Credentials
获取AWS凭证
python
import boto3
cognito_identity = boto3.client('cognito-identity')python
import boto3
cognito_identity = boto3.client('cognito-identity')Get identity ID
获取身份ID
response = cognito_identity.get_id(
IdentityPoolId='us-east-1:12345678-1234-1234-1234-123456789012',
Logins={
'cognito-idp.us-east-1.amazonaws.com/us-east-1_abc123': id_token
}
)
identity_id = response['IdentityId']
response = cognito_identity.get_id(
IdentityPoolId='us-east-1:12345678-1234-1234-1234-123456789012',
Logins={
'cognito-idp.us-east-1.amazonaws.com/us-east-1_abc123': id_token
}
)
identity_id = response['IdentityId']
Get credentials
获取凭证
response = cognito_identity.get_credentials_for_identity(
IdentityId=identity_id,
Logins={
'cognito-idp.us-east-1.amazonaws.com/us-east-1_abc123': id_token
}
)
credentials = response['Credentials']
response = cognito_identity.get_credentials_for_identity(
IdentityId=identity_id,
Logins={
'cognito-idp.us-east-1.amazonaws.com/us-east-1_abc123': id_token
}
)
credentials = response['Credentials']
Use credentials['AccessKeyId'], credentials['SecretKey'], credentials['SessionToken']
使用 credentials['AccessKeyId'], credentials['SecretKey'], credentials['SessionToken']
undefinedundefinedCLI Reference
CLI参考
User Pool
用户池
| Command | Description |
|---|---|
| Create user pool |
| Get pool details |
| Update pool settings |
| Delete pool |
| List pools |
| 命令 | 描述 |
|---|---|
| 创建用户池 |
| 获取用户池详情 |
| 更新用户池设置 |
| 删除用户池 |
| 列出用户池 |
Users
用户管理
| Command | Description |
|---|---|
| Create user (admin) |
| Delete user |
| Get user details |
| List users |
| Set password |
| Disable user |
| 命令 | 描述 |
|---|---|
| 管理员创建用户 |
| 管理员删除用户 |
| 获取用户详情 |
| 列出用户 |
| 设置用户密码 |
| 禁用用户 |
Authentication
认证相关
| Command | Description |
|---|---|
| Start authentication |
| Respond to MFA |
| Admin authentication |
| 命令 | 描述 |
|---|---|
| 发起认证流程 |
| 响应MFA挑战 |
| 管理员发起认证 |
Best Practices
最佳实践
Security
安全方面
- Enable MFA for all users (at least optional)
- Use strong password policies
- Enable advanced security features (adaptive auth)
- Verify email/phone before allowing sign-in
- Use short token lifetimes for sensitive apps
- Never expose client secrets in frontend code
- 为所有用户启用MFA(至少设为可选)
- 使用强密码策略
- 启用高级安全功能(自适应认证)
- 允许登录前验证邮箱/手机号
- 针对敏感应用缩短令牌有效期
- 切勿在前端代码中暴露客户端密钥
User Experience
用户体验
- Use hosted UI for quick implementation
- Customize UI with CSS
- Implement proper error handling
- Provide clear password requirements
- 使用托管UI快速实现登录功能
- 通过CSS自定义UI样式
- 实现完善的错误处理机制
- 提供清晰的密码要求说明
Architecture
架构设计
- Use identity pools for AWS resource access
- Use access tokens for API Gateway
- Store refresh tokens securely
- Implement token refresh before expiry
- 使用身份池实现AWS资源访问控制
- 使用Access Token访问API Gateway
- 安全存储Refresh Token
- 在令牌过期前实现自动刷新逻辑
Troubleshooting
故障排查
User Cannot Sign In
用户无法登录
Causes:
- User not confirmed
- Password incorrect
- User disabled
- Account locked (too many attempts)
Debug:
bash
aws cognito-idp admin-get-user \
--user-pool-id us-east-1_abc123 \
--username user@example.com可能原因:
- 用户未完成注册确认
- 密码错误
- 用户账号被禁用
- 账号因多次尝试失败被锁定
调试命令:
bash
aws cognito-idp admin-get-user \
--user-pool-id us-east-1_abc123 \
--username user@example.comToken Validation Failed
令牌验证失败
Causes:
- Token expired
- Wrong user pool/client ID
- Token signature invalid
Validate JWT:
python
import jwt
import requests可能原因:
- 令牌已过期
- 用户池/客户端ID不匹配
- 令牌签名无效
验证JWT:
python
import jwt
import requestsGet JWKS
获取JWKS
jwks_url = f'https://cognito-idp.us-east-1.amazonaws.com/us-east-1_abc123/.well-known/jwks.json'
jwks = requests.get(jwks_url).json()
jwks_url = f'https://cognito-idp.us-east-1.amazonaws.com/us-east-1_abc123/.well-known/jwks.json'
jwks = requests.get(jwks_url).json()
Decode and verify (use python-jose or similar)
解码并验证(推荐使用python-jose等库)
from jose import jwt
claims = jwt.decode(
token,
jwks,
algorithms=['RS256'],
audience='client-id',
issuer='https://cognito-idp.us-east-1.amazonaws.com/us-east-1_abc123'
)
undefinedfrom jose import jwt
claims = jwt.decode(
token,
jwks,
algorithms=['RS256'],
audience='client-id',
issuer='https://cognito-idp.us-east-1.amazonaws.com/us-east-1_abc123'
)
undefinedHosted UI Not Working
托管UI无法正常工作
Check:
- Callback URLs configured correctly
- Domain configured for user pool
- OAuth settings enabled
bash
undefined检查项:
- 回调URL配置正确
- 用户池已配置域名
- OAuth设置已启用
bash
undefinedCheck domain
检查用户池域名
aws cognito-idp describe-user-pool
--user-pool-id us-east-1_abc123
--query 'UserPool.Domain'
--user-pool-id us-east-1_abc123
--query 'UserPool.Domain'
undefinedaws cognito-idp describe-user-pool
--user-pool-id us-east-1_abc123
--query 'UserPool.Domain'
--user-pool-id us-east-1_abc123
--query 'UserPool.Domain'
undefinedRate Limiting
请求频率受限
Symptom:
TooManyRequestsExceptionSolutions:
- Implement exponential backoff
- Request quota increase
- Cache tokens appropriately
症状: 出现错误
TooManyRequestsException解决方案:
- 实现指数退避机制
- 请求提高配额
- 合理缓存令牌