Tuần 6 - Ngày 6: Amazon Cognito
Mục tiêu học tập
- Phân biệt User Pool và Identity Pool
- Hiểu authentication flow (JWT tokens)
- Nắm federation với social providers
- Áp dụng Cognito cho mobile/web apps
1. Tổng quan Cognito
Amazon Cognito = managed user identity service cho web + mobile apps.
2 components
| Component | Purpose |
|---|---|
| User Pool | User directory: signup, signin, password management |
| Identity Pool (Federated Identities) | Exchange identity → AWS temp credentials |
Use cases
- Mobile app authentication
- Web app SSO
- API authentication
- Backend user management without building auth
Pricing
- User Pool: $0.0055 per MAU (Monthly Active User), free tier 50K MAU
- Identity Pool: free
2. User Pool
Đặc điểm
- User directory (database of users)
- Authentication: username/password, email, phone
- MFA: SMS, TOTP, authenticator app
- Password policy: complexity, expiration
- Self-service: signup, password reset, email/phone verification
- Federation: SAML, OIDC (Google, Facebook, Apple, Amazon, SAML IdPs)
- Returns JWT tokens (ID token, Access token, Refresh token)
Token types
| Token | Contains | Use case |
|---|---|---|
| ID Token | User attributes (email, name, sub) | Identity verification |
| Access Token | Scopes, user info | API authorization |
| Refresh Token | (Opaque) | Get new ID/Access tokens |
Token lifetime
- ID Token: 1 hour (default)
- Access Token: 1 hour
- Refresh Token: 30 days (default, configurable 60 min - 10 years)
Customization
- Lambda triggers at key events:
- Pre Sign-up (validation)
- Post Confirmation
- Pre Authentication
- Post Authentication
- Custom Message (email/SMS content)
- Pre Token Generation (add custom claims)
App Client
- App accessing User Pool có app client ID
- Configure: which OAuth flows, which IdPs allowed, callback URLs
3. User Pool Authentication Flow
Standard flow
1. User → App: enters username + password
2. App → User Pool: InitiateAuth API
3. User Pool: verify creds
4. User Pool → App: ID Token + Access Token + Refresh Token (JWT)
5. App → API Gateway: API call với Access Token in Authorization header
6. API Gateway → User Pool: verify token signature
7. API Gateway → Lambda backend
Federated flow (Google sign-in)
1. User → App: "Sign in with Google"
2. App → Google: OAuth
3. Google → User Pool: SAML/OIDC token
4. User Pool: provision user (if first time)
5. User Pool → App: JWT tokens
4. Identity Pool (Federated Identities)
Đặc điểm
- Provide temporary AWS credentials to users
- For users authenticated via:
- Cognito User Pools
- Social IdPs (Google, Facebook, Apple, Amazon)
- SAML / OIDC
- Developer-authenticated
- 2 roles:
- Authenticated role
- Unauthenticated (guest) role
Workflow
1. User authenticates with IdP (User Pool, Google, ...)
2. IdP returns token
3. App calls Identity Pool: GetCredentialsForIdentity
4. Identity Pool returns AWS STS temp credentials
5. App uses credentials to access AWS services (S3, DynamoDB, API Gateway)
Use case: Mobile photo app
- User uploads photo directly to S3 (instead of through backend)
- Identity Pool gives temp credentials scoped to user's S3 prefix
- App uses creds for S3 upload
Policy scoping
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": ["s3:PutObject", "s3:GetObject"],
"Resource": "arn:aws:s3:::my-bucket/users/${cognito-identity.amazonaws.com:sub}/*"
}]
}
→ Each user can only access their own S3 prefix.
5. User Pool vs Identity Pool
| User Pool | Identity Pool | |
|---|---|---|
| Purpose | User management + auth | AWS credentials |
| Returns | JWT tokens | AWS temp credentials |
| For | App authentication | Direct AWS access |
| IdP | Optional (can federate) | Required (User Pool, social, SAML) |
| Combined use | Often combined: User Pool → Identity Pool → AWS |
Common pattern
User → User Pool (sign in) → JWT
→ Identity Pool (exchange JWT) → AWS temp creds
→ S3 / DynamoDB / API Gateway
6. Cognito with API Gateway
Cognito Authorizer
- API Gateway có Cognito Authorizer type
- Validates JWT token from User Pool
- No backend code needed for auth
Setup
Lambda Authorizer (alternative)
- Custom Lambda function validates token
- More flexible (custom logic)
- Use when need extra validation beyond Cognito
7. Cognito Federation Examples
Sign in with Google
- Setup Google OAuth credentials
- Add Google as IdP in User Pool
- Configure App Client allowed IdPs: Google
- User clicks "Sign in with Google" → redirects to Google → returns to app
SAML federation (corporate AD)
- Setup SAML IdP in User Pool (Okta, Azure AD, ADFS)
- Configure attribute mapping (email, name)
- Users sign in with corporate creds
Apple Sign-In
- Apple Developer account required
- Add Apple as IdP
- Handle Apple-specific tokens
8. Cognito Sync (Deprecated → use AppSync)
- Sync user data across devices
- Deprecated — use AWS AppSync + DataStore for new apps
9. Hosted UI
Định nghĩa
Hosted UI = AWS-provided customizable login/signup UI.
Đặc điểm
- Pre-built sign-in, sign-up, forgot password forms
- Customizable: logo, colors, CSS
- OAuth 2.0 flows: Authorization Code, Implicit, PKCE
- Custom domain support
Use case
- Don't want to build auth UI from scratch
- Quick prototype
- Standard auth flows
10. Advanced Security Features (Plus tier)
Risk-based adaptive authentication
- Detect risky sign-ins (new device, unusual location)
- Require MFA or block
Compromised credentials check
- Check against known compromised passwords
- Force user to change password
Pricing
- Plus tier: more expensive per MAU
11. Cognito vs IAM Identity Center vs IAM Users
| Cognito | IAM Identity Center | IAM Users | |
|---|---|---|---|
| For | App end-users | AWS workforce users | Legacy AWS access |
| Scale | Millions of users | 100s-1000s of employees | < 5000/account |
| SSO | Per app | Multi-account AWS | No |
| Use case | Mobile/web app users | Internal team accessing AWS | Legacy or service accounts |
Decision
- App users: Cognito
- Employees accessing AWS Console: IAM Identity Center
- Service accounts: IAM Roles (not users)
12. Common Patterns
Pattern 1: Mobile photo sharing app
User → Cognito User Pool (email/password)
→ Cognito Identity Pool (AWS creds scoped to user)
→ S3 upload + DynamoDB metadata
Pattern 2: SaaS multi-tenant app
Users → User Pool per tenant
→ API Gateway with Cognito Authorizer
→ Lambda → DynamoDB (filter by user ID from JWT)
Pattern 3: Enterprise app với SAML
Employee → User Pool with SAML federation (Okta)
→ JWT
→ App
Pattern 4: Public app + admin portal
Public users → User Pool A
Admins → User Pool B with MFA required
Different API Gateway authorizers
Câu hỏi ôn tập
-
User Pool và Identity Pool khác nhau ở điểm gì?
Xem đáp án
User Pool: authentication service — quản lý user directory (sign-up, sign-in, password reset, MFA, social federation). Trả về JWT tokens (ID, Access, Refresh). Không cấp AWS credentials. Identity Pool: authorization service — exchange identity (JWT từ User Pool, Google, Facebook, SAML) lấy temporary AWS credentials (via STS) để gọi AWS APIs trực tiếp. Thường dùng cả hai: User Pool authenticate → Identity Pool cấp AWS credentials.
-
JWT tokens trả về từ User Pool gồm những loại gì?
Xem đáp án
3 loại: (1) ID Token — chứa user attributes (email, phone, custom claims) — dùng để verify identity và pass user info đến backend, (2) Access Token — authorizes API calls đến User Pool (không phải AWS APIs) — chứa scopes và groups, (3) Refresh Token — lifetime dài (default 30 ngày) — dùng để lấy ID/Access tokens mới khi hết hạn. Refresh token không bao giờ gửi đến API — chỉ dùng với Cognito.
-
Khi nào dùng Identity Pool?
Xem đáp án
Khi cần mobile/web app gọi AWS APIs trực tiếp (S3 upload, DynamoDB query, Kinesis...) với temporary credentials. Ví dụ: app chụp ảnh cần upload thẳng lên S3 bucket của user — không qua backend server. Identity Pool cấp IAM role credentials với quyền limited scope. Cũng dùng cho unauthenticated (guest) access — cho phép anonymous users access AWS resources với quyền giới hạn.
-
Cognito Authorizer trong API Gateway validate gì?
Xem đáp án
Cognito Authorizer validate JWT Access Token từ User Pool. API Gateway check: (1) Token còn valid (không hết hạn), (2) Signature valid (signed bởi User Pool), (3) Token scope match required scopes (nếu cấu hình). Không cần code custom validation — API Gateway xử lý hoàn toàn. Nếu token invalid → 401 Unauthorized. Không cần Lambda Authorizer cho authentication flow đơn giản.
-
Cognito User Pool có hỗ trợ MFA không?
Xem đáp án
Có — Cognito User Pool hỗ trợ MFA: TOTP (Time-based One-Time Password — Google Authenticator, Authy) và SMS (qua Amazon SNS). Có thể cấu hình MFA là: Off, Optional (user tự chọn), hoặc Required (bắt buộc). Từ 2023, Cognito cũng hỗ trợ email OTP và passkeys (WebAuthn). MFA cấu hình ở User Pool level, không phải per-user.
Bài tập thực hành
- Tạo Cognito User Pool, configure password policy + MFA
- Tạo App Client, test sign-up + sign-in via Hosted UI
- Setup Identity Pool, get temp creds cho test user
- Configure API Gateway với Cognito Authorizer
- Add Google as federated IdP, test sign-in
- Tạo Lambda trigger Post-Confirmation: add user to DynamoDB
Tài liệu tham khảo chính thức
Tiếp theo: Quiz Tuần 6