cognito
itsmostafa/aws-agent-skills
AWS Cognito 사용자 풀, ID 풀, OAuth 플로우 및 사용자 인증을 CLI 명령과 Python SDK 예제를 사용하여 설정하고 관리합니다.
...모든 것을 확장하십시오AWS Cognito
Amazon Cognito는 웹 및 모바일 애플리케이션을 위한 인증, 권한 부여 및 사용자 관리를 제공합니다. 사용자는 직접 로그인하거나 연동된 신원 공급자를 통해 로그인할 수 있습니다.
목차
- 핵심 개념
- 일반적인 패턴
- CLI 참조
- 모범 사례
- 문제 해결
- 참조
핵심 개념
사용자 풀(User Pools)
로그인 및 회원가입을 위한 사용자 디렉토리입니다. 다음을 제공합니다:
- 사용자 등록 및 인증
- OAuth 2.0 / OpenID Connect 토큰
- 다중 인증(MFA) 및 비밀번호 정책
- 사용자 정의 가능한 UI 및 흐름
신원 풀(Identity Pools, 연동 신원)
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 # 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')
}
)
신원 풀 생성
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')
# 신원 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 참조
사용자 풀
| 명령어 | 설명 |
|---|---|
| `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` | MFA 응답 |
| `aws cognito-idp admin-initiate-auth` | 관리자 인증 |
모범 사례
보안
- 모든 사용자에게 MFA 활성화(최소 선택 사항)
- 강력한 비밀번호 정책 사용
- 고급 보안 기능 활성화(적응형 인증)
- 로그인 허용 전에 이메일/전화번호 확인
- 민감한 애플리케이션에는 짧은 토큨 유효 기간 사용
- 프론트엔드 코드에서 클라이언트 시크릿을 절대 노출하지 않음
사용자 경험
- 빠른 구현을 위해 호스팅 UI 사용
- 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
# 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'
)
호스팅 UI 작동 안 함
확인:
- 콜백 URL이 올바르게 구성되었는지 확인
- 사용자 풀에 도메인이 구성되었는지 확인
- OAuth 설정이 활성화되었는지 확인
# 도메인 확인
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/)





집
