Amazon Cognito
For the practical, code-level treatment (FastAPI JWT validation, token types, Lambda triggers, refresh rotation), see backend/11_authentication/03_cognito_python.md. This file is the AWS-service overview.
Overview
Amazon Cognito provides authentication, authorization, and user management for your web and mobile apps. It consists of two main components: User Pools and Identity Pools. User Pools provide sign-up and sign-in functionality, while Identity Pools provide temporary AWS credentials to access AWS services.
Key Features
- User Pools: User directory and authentication service
- Identity Pools: Temporary AWS credentials for authenticated users
- Social Identity Providers: Facebook, Google, Amazon, Apple
- Multi-Factor Authentication (MFA): SMS, TOTP, email
- Password Policies: Customizable password requirements
- User Migration: Import existing users
- Lambda Triggers: Custom authentication flows
- Federation: SAML, OAuth 2.0, OpenID Connect
Interview Topics
1. User Pools
- User Directory: Centralized user management
- Sign-up/Sign-in: Built-in authentication flows
- Password Policies: Security requirements
- MFA Options: SMS, TOTP, email verification
- User Attributes: Custom and standard attributes
2. Identity Pools
- Temporary Credentials: AWS credentials for users
- Role Mapping: Assign IAM roles based on identity
- Federation: Integrate with external identity providers
- Guest Access: Unauthenticated user access
- Credential Management: Automatic credential refresh
3. Authentication Flows
- SRP (Secure Remote Password): Secure password verification
- OAuth 2.0: Authorization code flow
- OpenID Connect: Identity layer on OAuth 2.0
- SAML: Enterprise federation
- Custom Authentication: Lambda-based flows
4. Security Features
- MFA: Multi-factor authentication
- Password Policies: Strength requirements
- Account Recovery: Self-service password reset
- Risk-Based Authentication: Adaptive authentication
- Compliance: GDPR, HIPAA, SOC compliance
5. Integration Patterns
- Web Applications: JavaScript SDK integration
- Mobile Applications: iOS/Android SDKs
- API Gateway: Lambda authorizer integration
- AWS Services: Direct service integration
- Third-party Apps: OAuth/SAML integration
Common Interview Questions
Basic Questions
-
What is Amazon Cognito and what are its main components?
- User Pools: User directory and authentication
- Identity Pools: Temporary AWS credentials
- Provides complete authentication solution
- Supports social and enterprise identity providers
-
What is the difference between User Pools and Identity Pools?
- User Pools: User directory, sign-up/sign-in, MFA
- Identity Pools: Temporary AWS credentials, federation
- User Pools handle authentication
- Identity Pools handle authorization
-
How do you create a User Pool?
aws cognito-idp create-user-pool \ --pool-name "MyUserPool" \ --policies PasswordPolicy={MinimumLength=8,RequireUppercase=true,RequireLowercase=true,RequireNumbers=true,RequireSymbols=true}
Advanced Questions
-
How do you implement custom authentication with Lambda triggers?
import boto3 import json def lambda_handler(event, context): # Custom authentication logic if event['triggerSource'] == 'DefineAuthChallenge_Authentication': # Define authentication challenge event['response']['challengeName'] = 'CUSTOM_CHALLENGE' event['response']['issueTokens'] = False event['response']['failAuthentication'] = False elif event['triggerSource'] == 'CreateAuthChallenge_Authentication': # Create custom challenge event['response']['challengeMetadata'] = 'CUSTOM_CHALLENGE' elif event['triggerSource'] == 'VerifyAuthChallengeResponse_Authentication': # Verify challenge response expected_answer = event['request']['privateChallengeParameters']['answer'] user_answer = event['request']['challengeAnswer'] if user_answer == expected_answer: event['response']['answerCorrect'] = True else: event['response']['answerCorrect'] = False return event -
How do you integrate Cognito with API Gateway?
- Use Cognito User Pool authorizer
- Configure JWT token validation
- Set up proper IAM roles
- Handle token refresh
-
How do you implement social login with Cognito?
- Configure identity providers (Facebook, Google, etc.)
- Set up app client with social providers
- Handle OAuth flow
- Map social attributes to user attributes
Troubleshooting Questions
-
What if users can’t sign in to your application?
- Check User Pool configuration
- Verify app client settings
- Review authentication flow
- Check Lambda triggers
-
How do you handle token expiration and refresh?
- Implement token refresh logic
- Use refresh tokens
- Handle token validation
- Monitor token lifecycle
Best Practices
1. Security
- Implement strong password policies
- Enable MFA for all users
- Use HTTPS for all communications
- Regularly rotate app client secrets
2. User Experience
- Implement progressive profiling
- Use appropriate MFA methods
- Provide clear error messages
- Support account recovery
3. Performance
- Use appropriate token expiration times
- Implement proper caching
- Monitor authentication performance
- Optimize Lambda triggers
4. Compliance
- Implement data retention policies
- Support user data export/deletion
- Maintain audit trails
- Ensure regulatory compliance
5. Monitoring
- Set up CloudWatch alarms
- Monitor authentication metrics
- Track user activity
- Alert on security events
Use Cases
1. Web Applications
- User registration and login
- Social media integration
- MFA implementation
- Session management
2. Mobile Applications
- Native authentication
- Biometric authentication
- Offline authentication
- Push notifications
3. Enterprise Applications
- SAML federation
- Active Directory integration
- Single sign-on (SSO)
- Role-based access control
4. API Security
- JWT token validation
- API Gateway integration
- Microservices authentication
- Service-to-service auth
Integration Patterns
1. Web Application Integration
- JavaScript SDK
- React/Angular integration
- Server-side validation
- Session management
2. Mobile Application Integration
- iOS/Android SDKs
- Biometric authentication
- Offline capabilities
- Push notifications
3. API Gateway Integration
- Cognito authorizer
- JWT validation
- Role mapping
- Token refresh
4. AWS Service Integration
- Direct service access
- IAM role assumption
- Cross-account access
- Service-to-service auth
Security Considerations
1. Authentication Security
- Implement strong MFA
- Use secure password policies
- Monitor authentication attempts
- Implement account lockout
2. Token Security
- Use appropriate token expiration
- Implement secure token storage
- Validate tokens properly
- Handle token refresh securely
3. Data Protection
- Encrypt sensitive data
- Implement data retention
- Support user privacy rights
- Monitor data access
4. Compliance
- Maintain audit trails
- Support data portability
- Implement access controls
- Regular security assessments
Cost Optimization
1. User Pool Optimization
- Monitor user count
- Optimize Lambda triggers
- Use appropriate MFA methods
- Monitor authentication costs
2. Identity Pool Optimization
- Optimize credential usage
- Monitor AWS service access
- Use appropriate role policies
- Track federation costs
3. Storage Optimization
- Optimize user attributes
- Implement data retention
- Monitor storage usage
- Clean up unused data
4. API Optimization
- Optimize token refresh
- Monitor API calls
- Use appropriate caching
- Track integration costs
Performance Optimization
1. Authentication Performance
- Optimize Lambda triggers
- Use appropriate caching
- Monitor response times
- Implement connection pooling
2. Token Management
- Optimize token expiration
- Implement efficient refresh
- Monitor token validation
- Use appropriate algorithms
3. User Experience
- Minimize authentication steps
- Optimize MFA flows
- Implement progressive profiling
- Monitor user satisfaction
4. Scalability
- Design for horizontal scaling
- Monitor capacity limits
- Implement auto-scaling
- Plan for growth
Disaster Recovery
1. Data Backup
- Backup user data
- Maintain configuration backups
- Document recovery procedures
- Test recovery processes
2. Service Continuity
- Monitor service health
- Implement failover procedures
- Use multi-region deployment
- Maintain operational procedures
3. User Access
- Ensure authentication availability
- Implement backup authentication
- Monitor access patterns
- Maintain user support
4. Compliance Continuity
- Maintain audit trails
- Ensure data protection
- Support regulatory requirements
- Monitor compliance status
Migration Strategies
1. From Custom Authentication
- Map existing user data
- Implement equivalent flows
- Migrate users gradually
- Test thoroughly
2. From Other Auth Providers
- Map authentication flows
- Implement equivalent features
- Migrate user data
- Validate functionality
3. Application Migration
- Plan authentication requirements
- Configure Cognito services
- Migrate applications
- Test authentication flows
Common Pitfalls
1. Security Issues
- Weak password policies
- Inadequate MFA
- Poor token management
- Insufficient monitoring
2. User Experience Problems
- Complex authentication flows
- Poor error handling
- Inadequate user support
- Performance issues
3. Integration Issues
- Incorrect SDK usage
- Poor error handling
- Inadequate testing
- Performance problems
4. Compliance Issues
- Inadequate audit trails
- Poor data protection
- Insufficient monitoring
- Compliance violations
Resources
- Amazon Cognito Documentation
- Cognito User Pools Developer Guide
- Cognito Identity Pools Developer Guide
Interview angle
- “User pool or identity pool?” - a user pool is the directory and issues tokens; an identity pool exchanges tokens for temporary AWS credentials so a client can call AWS services directly. Most applications need only the user pool.
- “What are the three tokens for?” - the ID token carries identity claims and is for your application; the access token authorises API calls and is what your backend validates; the refresh token obtains new ones. Sending the ID token as the API credential is a common mix-up.
- “How does your backend validate a token?” - verify the signature against the pool’s JWKS, then check issuer, audience,
token_useand expiry. Cache the JWKS; do not fetch it per request. - “Cognito or Auth0/Okta/Keycloak?” - Cognito when you are AWS-native, want low cost at scale and tight IAM integration. The others when you need richer enterprise SSO, better admin tooling, or portability. Cognito’s customisation limits are the usual reason teams move off it.
- “How do you handle MFA and passkeys?” - Cognito supports TOTP and SMS MFA, and WebAuthn passkeys. Passkeys are the direction of travel and worth naming - phishing-resistant by design, unlike SMS. See ../../../11_authentication/.