Skip to main content

Amazon Cognito

Core concept: Cognito handles AuthN (who are you?) via User Pools and AuthZ (what can you access in AWS?) via Identity Pools.


User Pools vs Identity Poolsโ€‹

FeatureUser PoolIdentity Pool
PurposeAuthenticate users (sign up / sign in)Grant AWS credentials to authenticated users
ReturnsJWT tokens (ID, Access, Refresh)Temporary AWS credentials (via STS)
Use caseLog into your appCall AWS services (S3, DynamoDB) directly
Think of it asYour app's user directory + OAuth serverAWS IAM role vending machine
Analogy
  • User Pool = Your bouncer โ€” checks the guest list
  • Identity Pool = The VIP key card โ€” unlocks AWS services

User Pool Deep Diveโ€‹

What It Providesโ€‹

  • Sign-up / Sign-in UI (Hosted UI)
  • Email/phone verification
  • MFA (TOTP, SMS)
  • Password policies
  • Lambda triggers (pre-signup, post-confirmation, pre-token generation...)
  • Federation with social IdPs: Google, Facebook, Apple, Amazon
  • Federation with corporate IdPs: SAML 2.0, OIDC

JWT Token Typesโ€‹

TokenExpiryUse
ID Token1 hourUser identity claims (email, sub, custom attributes)
Access Token1 hourAuthorize API calls (used with API Gateway Cognito Authorizer)
Refresh TokenUp to 10 yearsGet new ID/Access tokens without re-login

Lambda Triggers (Exam Favorite!)โ€‹

TriggerWhen firedCommon Use
Pre Sign-upBefore user is confirmedBlock certain email domains
Post ConfirmationAfter user confirms emailAdd user to DynamoDB
Pre AuthenticationBefore sign-inCustom validation
Post AuthenticationAfter sign-inAudit logging
Pre Token GenerationBefore issuing tokensAdd custom claims to JWT
Custom MessageBefore sending verification email/SMSBrand the message
User MigrationWhen user doesn't exist in User PoolMigrate from legacy auth

Identity Pool Deep Diveโ€‹

Flowโ€‹

User authenticates with User Pool (or Google/Facebook)
โ”‚
โ–ผ
Gets JWT token
โ”‚
โ–ผ
Calls Cognito Identity Pool with JWT
โ”‚
โ–ผ
Identity Pool calls STS:AssumeRoleWithWebIdentity
โ”‚
โ–ผ
Returns temporary AWS credentials (AccessKey + SecretKey + SessionToken)
โ”‚
โ–ผ
User calls AWS APIs directly (S3, DynamoDB, etc.)

IAM Roles in Identity Poolsโ€‹

  • Authenticated Role โ€” permissions for logged-in users
  • Unauthenticated Role โ€” permissions for guest/anonymous users
  • Role Mapping โ€” assign different roles based on user attributes (group membership, custom claims)

API Gateway + Cognito Authorizerโ€‹

Client โ†’ API Gateway โ†’ Cognito User Pool Authorizer โ†’ Validates JWT โ†’ Lambda
  • API Gateway extracts the Bearer token from the Authorization header
  • Verifies signature against User Pool's JWKS endpoint
  • Returns 401 if invalid/expired

Java SDK โ€” Authenticating a Userโ€‹

import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient;
import software.amazon.awssdk.services.cognitoidentityprovider.model.*;

var client = CognitoIdentityProviderClient.create();

var authResult = client.initiateAuth(InitiateAuthRequest.builder()
.authFlow(AuthFlowType.USER_PASSWORD_AUTH)
.clientId("your-app-client-id")
.authParameters(Map.of(
"USERNAME", "user@example.com",
"PASSWORD", "SecretPass123!"
))
.build());

String idToken = authResult.authenticationResult().idToken();
String accessToken = authResult.authenticationResult().accessToken();
String refreshToken = authResult.authenticationResult().refreshToken();

๐Ÿงช Practice Questionsโ€‹

Q1. A mobile app stores photos in S3. Users authenticate with Google Sign-In. The app needs to upload directly to S3. Which Cognito component provides the temporary AWS credentials?

A) Cognito User Pool
B) Cognito Identity Pool
C) Cognito Sync
D) Cognito Lambda Trigger

โœ… Answer & Explanation

B โ€” The Identity Pool federates the Google JWT and calls STS to return temporary AWS credentials. The User Pool handles authentication; the Identity Pool handles AWS authorization.


Q2. A developer wants to add custom attributes (e.g., tenant_id) to JWT tokens issued by Cognito. Which Lambda trigger should they use?

A) Post Confirmation
B) Pre Authentication
C) Pre Token Generation
D) Custom Message

โœ… Answer & Explanation

C โ€” Pre Token Generation fires just before Cognito issues tokens, allowing you to add/override claims in the ID and Access tokens.


Q3. What is the default expiry of a Cognito User Pool Access Token?

A) 5 minutes
B) 30 minutes
C) 1 hour
D) 24 hours

โœ… Answer & Explanation

C โ€” Access and ID tokens expire in 1 hour by default. Refresh tokens can last up to 10 years (configurable).


Q4. A company wants to allow unauthenticated (guest) users to read public content from S3 via the mobile app. Which feature enables this?

A) User Pool Guest Mode
B) Identity Pool Unauthenticated Identities
C) S3 Public Access
D) Lambda@Edge

โœ… Answer & Explanation

B โ€” Enable Unauthenticated Identities in the Identity Pool. Assign a limited IAM role (e.g., S3 read-only on public prefix) to the unauthenticated role.


๐Ÿ”— Resourcesโ€‹