cognito
itsmostafa/aws-agent-skills
透過 CLI 指令和 Python SDK 範例,設定並管理 AWS Cognito 使用者群組、身分識別群組、OAuth 流程以及使用者驗證。
...展開全部AWS Cognito
Amazon Cognito 為網頁和行動應用程式提供身分驗證、授權及使用者管理功能。使用者可直接登入,或透過聯邦身分識別供應商進行登入。
目錄
- 核心概念
- 常見模式
- CLI 參考手冊
- 最佳實務
- 疑難排解
- 參考資料
核心概念
使用者群組
用於註冊與登入的使用者目錄。提供:
- 使用者註冊與驗證
- OAuth 2.0 / OpenID Connect 憑證
- 多因素驗證 (MFA) 及密碼政策
- 可自訂的使用者介面與流程
身分識別池(聯邦身分識別)
提供臨時 AWS 憑證以存取 AWS 服務。使用者可為:
- Cognito 使用者池中的使用者
- 社交身分(Google、Facebook、Apple)
- SAML/OIDC 企業身分
- 匿名訪客
憑證
| 憑證 | 用途 | 有效期 |
|---|---|---|
| ID 代幣 | 使用者身分聲明 | 1 小時 |
| 存取憑證 | API 授權 | 1 小時 |
| 刷新憑證 | 取得新的 ID/存取憑證 | 30 天(可設定) |
常見模式
建立使用者池
AWS CLI:
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 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"
}'
註冊使用者
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 # 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']
刷新憑證
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')
}
)
建立身分識別池
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
取得 AWS 憑證
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 參考手冊
使用者池
| 指令 | 說明 |
|---|---|
aws cognito-idp create-user-pool |
建立使用者群組 |
aws cognito-idp describe-user-pool |
取得使用者群組詳細資料 |
aws cognito-idp update-user-pool |
更新池設定 |
aws cognito-idp delete-user-pool |
刪除使用者池 |
aws cognito-idp list-user-pools |
列出使用者群組 |
使用者
| 指令 | 說明 |
|---|---|
aws cognito-idp admin-create-user |
建立使用者 (管理員) |
aws cognito-idp admin-delete-user |
刪除使用者 |
aws cognito-idp admin-get-user |
取得使用者詳細資料 |
aws cognito-idp list-users |
列出使用者 |
aws cognito-idp admin-set-user-password |
設定密碼 |
aws cognito-idp admin-disable-user |
停用使用者 |
驗證
| 指令 | 說明 |
|---|---|
aws cognito-idp initiate-auth |
啟動驗證 |
aws cognito-idp respond-to-auth-challenge |
回應多重因素驗證 |
aws cognito-idp admin-initiate-auth |
管理員驗證 |
最佳實務
安全性
- 為所有使用者啟用多因素驗證(至少設定為「可選」)
- 採用強密碼政策
- 啟用進階安全性功能(自適應驗證)
- 在允許登入前驗證電子郵件/手機號碼
- 針對敏感應用程式設定較短的憑證有效期
- 切勿在前端程式碼中暴露客戶端密鑰
使用者體驗
- 使用託管式使用者介面以快速實作
- 使用 CSS 自訂 UI
- 實作適當的錯誤處理機制
- 提供明確的密碼設定規範
架構
- 使用身分識別池存取 AWS 資源
- 使用存取憑證連線至 API Gateway
- 安全地儲存刷新憑證
- 在過期前實作憑證更新
疑難排解
使用者無法登入
原因:
- 用戶尚未完成確認
- 密碼錯誤
- 使用者已停用
- 帳戶遭鎖定(嘗試次數過多)
除錯:
aws cognito-idp admin-get-user \
--user-pool-id us-east-1_abc123 \
--username [email protected]
憑證驗證失敗
原因:
- 憑證已過期
- 使用者群組/客戶端 ID 錯誤
- 憑證簽名無效
驗證 JWT:
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'
)
託管式使用者介面無法運作
請檢查:
- 回呼網址是否設定正確
- 已為使用者群組設定網域
- 已啟用 OAuth 設定
# Check domain
aws cognito-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/)





首頁
