Cognito & Authentication
Implement user authentication with Amazon Cognito — user pools for identity management, identity pools for AWS access, and social/OIDC federation.
Cognito User Pools
User Pools are user directories that handle sign-up, sign-in, MFA, password recovery, and profile management. They issue JWT tokens (ID, access, refresh) for authenticated sessions.
Integrate with API Gateway authorizers, ALB authentication, or validate tokens in application code. Supports email, phone, and username sign-in.
- Free tier: 50,000 MAU (Monthly Active Users)
- Built-in UI hosted by AWS or custom UI with SDK
- Supports MFA: SMS, TOTP (authenticator apps)
// Sign in with Amplify
import { signIn } from 'aws-amplify/auth';
const { isSignedIn, nextStep } = await signIn({
username: 'user@example.com',
password: 'SecurePass123!',
});
// Returns JWT tokens on success
// ID token: user identity claims
// Access token: API authorization
// Refresh token: obtain new tokensUser Pool Configuration
Configure password policies, attribute requirements, and verification methods. Add custom attributes for application-specific data. Set up Lambda triggers for custom workflows: pre-sign-up validation, post-confirmation actions, and custom message templates.
App clients define allowed authentication flows and token expiration. Create separate clients for web, mobile, and server applications.
# Create user pool with email sign-in
aws cognito-idp create-user-pool \
--pool-name MyAppUsers \
--policies '{
"PasswordPolicy": {
"MinimumLength": 12,
"RequireUppercase": true,
"RequireNumbers": true,
"RequireSymbols": true
}
}' \
--auto-verified-attributes email \
--mfa-configuration OPTIONALSocial and OIDC Federation
Cognito federates with social identity providers (Google, Facebook, Apple) and enterprise OIDC/SAML providers (Okta, Azure AD). Users sign in with existing credentials; Cognito maps external attributes to user pool profiles.
Configure identity provider credentials in the user pool. Add hosted UI buttons for social sign-in. Map provider attributes to Cognito standard and custom attributes.
# Add Google as identity provider
aws cognito-idp create-identity-provider \
--user-pool-id us-east-1_ABC123 \
--provider-name Google \
--provider-type Google \
--provider-details \
client_id=GOOGLE_CLIENT_ID \
client_secret=GOOGLE_CLIENT_SECRET \
--attribute-mapping email=email,name=name,picture=pictureIdentity Pools and AWS Access
Identity Pools provide temporary AWS credentials to authenticated and unauthenticated users. Map user pool tokens to IAM roles with fine-grained permissions.
Use Identity Pools when applications need direct AWS service access — uploading to S3, reading from DynamoDB. User Pools alone only provide authentication tokens.
// Get temporary AWS credentials via Identity Pool
import { fetchAuthSession } from 'aws-amplify/auth';
const session = await fetchAuthSession();
const credentials = session.credentials;
// credentials.accessKeyId, secretAccessKey, sessionToken
// Use with AWS SDK clients directlyAPI Gateway Authorization
Protect API Gateway endpoints with Cognito User Pool authorizers. Clients include the access token in the Authorization header. API Gateway validates the JWT before invoking Lambda.
Configure authorizer on API routes. Set token source to Authorization header. Unauthorized requests receive 401 before reaching backend code.
- Validate JWT in Lambda if not using API Gateway authorizer
- Use aws-jwt-verify library for token validation in Node.js
- Refresh tokens before expiry to maintain sessions
# API Gateway Cognito authorizer
aws apigatewayv2 create-authorizer \
--api-id abc123 \
--authorizer-type JWT \
--identity-source '$request.header.Authorization' \
--jwt-configuration '{
"Audience": ["app-client-id"],
"Issuer": "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_ABC123"
}'Security Best Practices
Enable advanced security features: adaptive authentication (risk-based), compromised credentials detection, and account takeover protection. Require MFA for sensitive operations.
Use short token expiration (1 hour access, 30 days refresh). Implement token refresh in client applications. Never store tokens in localStorage — use httpOnly cookies or secure storage on mobile.
// Secure token storage pattern // Web: httpOnly secure cookies (set by backend) // Mobile: Keychain (iOS) / EncryptedSharedPreferences (Android) // Never: localStorage, sessionStorage, plain cookies