cognito
itsmostafa/aws-agent-skills
使用 CLI 命令和 Python SDK 示例来配置和管理 AWS Cognito 用户池、身份池、OAuth 流程以及用户身份验证。
...展开全部AWSCognito
亚马逊Cognito 为Web和移动应用程序提供身份验证、授权及用户管理服务。用户可以直接登录,也可以通过联合身份提供商登录。
目录
- 核心概念
- 常见模式
- CLI 参考
- 最佳实践
- 故障排除
- 参考资料
核心概念
用户池
用于注册和登录的用户目录。提供:
- 用户注册和身份验证
- OAuth 2.0 / OpenID Connect 令牌
- 多因素认证(MFA)和密码策略
- 可自定义的用户界面和流程
身份池(联合身份)
提供临时 AWS 凭证以访问 AWS 服务。用户可以是:
- Cognito 用户池中的用户
- 社交身份(Google、Facebook、Apple)
- SAML/OIDC 企业身份
- 匿名访客
令牌
| 令牌 | 用途 | 有效期 |
|---|---|---|
| ID 令牌 | 用户身份声明 | 1 小时 |
| 访问令牌 | API授权 | 1小时 |
| 刷新令牌 | 获取新的ID/访问令牌 | 30天(可配置) |
常见模式
创建用户池
AWS CLI:
awscognito-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 可选 \
--user-attribute-update-settings '{
"AttributesRequireVerificationBeforeUpdate": ["email"]
}'
创建应用客户端
awscognito-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-providersCOGNITO \
--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"
}'
注册用户
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('[email protected]', 'client-id', 'client-secret'),
Username='[email protected]',
Password='SecurePassword123!',
UserAttributes=[
{'Name': 'email', 'Value': '[email protected]'},
{'Name': 'name', 'Value': 'John Doe'}
]
)
确认注册
cognito.confirm_sign_up(
ClientId='client-id',
SecretHash=get_secret_hash('[email protected]', 'client-id', 'client-secret'),
Username='[email protected]',
ConfirmationCode='123456'
)
验证用户
response =cognito.initiate_auth(
ClientId='client-id',
AuthFlow='USER_SRP_AUTH',
AuthParameters={
'USERNAME': '[email protected]',
'SECRET_HASH': get_secret_hash('[email protected]', 'client-id', 'client-secret'),
'SRP_A': srp_a # 来自 SRP 库
}
)
# 用于简单的密码认证(不建议在生产环境中使用)
response =cognito.admin_initiate_auth(
UserPoolId='us-east-1_abc123',
ClientId='client-id',
AuthFlow='ADMIN_USER_PASSWORD_AUTH',
AuthParameters={
'USERNAME': '[email protected]',
'PASSWORD': 'password',
'SECRET_HASH': get_secret_hash('[email protected]', 'client-id', 'client-secret')
}
)
tokens = response['AuthenticationResult']
id_token = tokens['IdToken']
access_token = tokens['AccessToken']
refresh_token = tokens['RefreshToken']
刷新令牌
response =cognito.initiate_auth(
ClientId='client-id',
AuthFlow='REFRESH_TOKEN_AUTH',
AuthParameters={
'REFRESH_TOKEN': refresh_token,
'SECRET_HASH': get_secret_hash('[email protected]', 'client-id', 'client-secret')
}
)
创建身份池
awscognito-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=true
获取 AWS 凭证
import boto3
cognito_identity = boto3.client('cognito-identity')
# 获取身份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_credentials_for_identity(
IdentityId=identity_id,
Logins={
'cognito-idp.us-east-1.amazonaws.com/us-east-1_abc123': id_token
}
)
credentials = response['Credentials']
# 使用 credentials['AccessKeyId'], credentials['SecretKey'], credentials['SessionToken']
CLI 参考
用户池
| 命令 | 描述 |
|---|---|
awscognito-idp create-user-pool |
创建用户池 |
awscognito-idp describe-user-pool |
获取用户池详细信息 |
awscognito-idp update-user-pool |
更新用户池设置 |
awscognito-idp delete-user-pool |
删除用户池 |
awscognito-idp list-user-pools |
列出用户池 |
用户
| 命令 | 描述 |
|---|---|
awscognito-idp admin-create-user |
创建用户(管理员) |
awscognito-idp admin-delete-user |
删除用户 |
awscognito-idp admin-get-user |
获取用户详细信息 |
awscognito-idp list-users |
列出用户 |
awscognito-idp admin-set-user-password |
设置密码 |
awscognito-idp admin-disable-user |
禁用用户 |
身份验证
| 命令 | 描述 |
|---|---|
awscognito-idp initiate-auth |
开始身份验证 |
awscognito-idp respond-to-auth-challenge |
响应多因素身份验证 |
awscognito-idp admin-initiate-auth |
管理员身份验证 |
最佳实践
安全性
- 为所有用户启用 MFA(至少设置为可选)
- 采用强密码策略
- 启用高级安全功能(自适应身份验证)
- 在允许登录前验证电子邮件/手机号码
- 对敏感应用使用较短的令牌有效期
- 切勿在前端代码中暴露客户端密钥
用户体验
- 使用托管式用户界面以实现快速部署
- 使用 CSS自定义 UI
- 实现正确的错误处理
- 提供清晰的密码要求
架构
- 使用身份池访问 AWS 资源
- 在 API Gateway中使用访问令牌
- 安全地存储刷新令牌
- 在令牌过期前实施令牌刷新
故障排除
用户无法登录
原因:
- 用户未通过验证
- 密码错误
- 用户已被禁用
- 账户已被锁定(尝试登录次数过多)
调试:
awscognito-idp admin-get-user \
--user-pool-id us-east-1_abc123 \
--username [email protected]
令牌验证失败
原因:
- 令牌已过期
- 用户池/客户端 ID 错误
- 令牌签名无效
验证 JWT:
import jwt
import requests
# 获取 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()
# 解码并验证(使用 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'
)
托管式用户界面无法正常工作
请检查:
- 回调 URL 配置是否正确
- 是否为用户池配置了域名
- 是否已启用 OAuth 设置
# 检查域名
awscognito-idp describe-user-pool \
--user-pool-id us-east-1_abc123 \
--query 'UserPool.Domain'
速率限制
症状: TooManyRequestsException
解决方案:
- 实现指数退避
- 提高请求配额
- 合理缓存令牌
参考资料
- Cognito 开发者指南
- Cognito 用户池 API
- Cognito 身份 API
- Cognito CLI 参考
---
name: cognito
description: Set up and manage AWS Cognito user pools, identity pools, OAuth flows, and user authentication with CLI commands and Python SDK examples.
---
# 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.
## Table of Contents
- [Core Concepts](#core-concepts)
- [Common Patterns](#common-patterns)
- [CLI Reference](#cli-reference)
- [Best Practices](#best-practices)
- [Troubleshooting](#troubleshooting)
- [References](#references)
## 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
### 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
### 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) |
## 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"]
}'
```
### 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"
}'
```
### 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('[email protected]', 'client-id', 'client-secret'),
Username='[email protected]',
Password='SecurePassword123!',
UserAttributes=[
{'Name': 'email', 'Value': '[email protected]'},
{'Name': 'name', 'Value': 'John Doe'}
]
)
```
### Confirm Sign Up
```python
cognito.confirm_sign_up(
ClientId='client-id',
SecretHash=get_secret_hash('[email protected]', 'client-id', 'client-secret'),
Username='[email protected]',
ConfirmationCode='123456'
)
```
### Authenticate User
```python
response = cognito.initiate_auth(
ClientId='client-id',
AuthFlow='USER_SRP_AUTH',
AuthParameters={
'USERNAME': '[email protected]',
'SECRET_HASH': get_secret_hash('[email protected]', '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': '[email protected]',
'PASSWORD': 'password',
'SECRET_HASH': get_secret_hash('[email protected]', 'client-id', 'client-secret')
}
)
tokens = response['AuthenticationResult']
id_token = tokens['IdToken']
access_token = tokens['AccessToken']
refresh_token = tokens['RefreshToken']
```
### Refresh Tokens
```python
response = cognito.initiate_auth(
ClientId='client-id',
AuthFlow='REFRESH_TOKEN_AUTH',
AuthParameters={
'REFRESH_TOKEN': refresh_token,
'SECRET_HASH': get_secret_hash('[email protected]', '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=true
```
### Get AWS Credentials
```python
import boto3
cognito_identity = boto3.client('cognito-identity')
# Get identity 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']
# 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']
# Use credentials['AccessKeyId'], credentials['SecretKey'], credentials['SessionToken']
```
## CLI Reference
### User Pool
| Command | Description |
|---------|-------------|
| `aws cognito-idp create-user-pool` | Create user pool |
| `aws cognito-idp describe-user-pool` | Get pool details |
| `aws cognito-idp update-user-pool` | Update pool settings |
| `aws cognito-idp delete-user-pool` | Delete pool |
| `aws cognito-idp list-user-pools` | List pools |
### Users
| Command | Description |
|---------|-------------|
| `aws cognito-idp admin-create-user` | Create user (admin) |
| `aws cognito-idp admin-delete-user` | Delete user |
| `aws cognito-idp admin-get-user` | Get user details |
| `aws cognito-idp list-users` | List users |
| `aws cognito-idp admin-set-user-password` | Set password |
| `aws cognito-idp admin-disable-user` | Disable user |
### Authentication
| Command | Description |
|---------|-------------|
| `aws cognito-idp initiate-auth` | Start authentication |
| `aws cognito-idp respond-to-auth-challenge` | Respond to MFA |
| `aws cognito-idp admin-initiate-auth` | Admin authentication |
## 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
### User Experience
- **Use hosted UI** for quick implementation
- **Customize UI** with CSS
- **Implement proper error handling**
- **Provide clear password requirements**
### Architecture
- **Use identity pools** for AWS resource access
- **Use access tokens** for API Gateway
- **Store refresh tokens securely**
- **Implement token refresh** before expiry
## 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 [email protected]
```
### Token Validation Failed
**Causes:**
- Token expired
- Wrong user pool/client ID
- Token signature invalid
**Validate JWT:**
```python
import jwt
import requests
# Get 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()
# Decode and verify (use python-jose or similar)
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'
)
```
### Hosted UI Not Working
**Check:**
- Callback URLs configured correctly
- Domain configured for user pool
- OAuth settings enabled
```bash
# Check domain
aws cognito-idp describe-user-pool \
--user-pool-id us-east-1_abc123 \
--query 'UserPool.Domain'
```
### Rate Limiting
**Symptom:** `TooManyRequestsException`
**Solutions:**
- Implement exponential backoff
- Request quota increase
- Cache tokens appropriately
## References
- [Cognito Developer Guide](https://docs.aws.amazon.com/cognito/latest/developerguide/)
- [Cognito User Pools API](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/)
- [Cognito Identity API](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/)
- [Cognito CLI Reference](https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/)





首页
