DVA-C02Chapter 8 of 101Objective 2.2

Amazon Cognito

This chapter covers Amazon Cognito, the primary AWS service for implementing authentication, authorization, and user management in modern applications. For the DVA-C02 exam, Cognito is a high-frequency topic, appearing in roughly 10-15% of questions across security, serverless, and mobile domains. You must understand the distinct roles of User Pools and Identity Pools, token formats and validation, federation, and integration with API Gateway and ALB. This chapter provides the deep technical knowledge needed to answer any Cognito question on the exam.

25 min read
Intermediate
Updated May 31, 2026

Cognito as a Hotel Key Card System

Amazon Cognito is like a hotel's key card system. When you check in, the front desk (Cognito User Pools) verifies your identity (username/password, social login, or OTP) and issues you a key card (ID token, access token, refresh token). This key card has specific permissions: your room number, floor access, pool hours, etc. (JWT claims). For extra security, the front desk may ask for a second form of ID (multi-factor authentication, MFA) before issuing the key. Now, you walk to the elevator (your app's backend). The elevator doesn't need to call the front desk every time you swipe; it just reads the card's magnetic stripe (validates the JWT signature using the public key from the user pool's JWKS endpoint). The card expires at 11 AM on checkout day (token expiry, default 1 hour for access tokens). If you want to stay longer, you go to a kiosk (Cognito's refresh token endpoint) and get a new card without re-entering your password. Meanwhile, the hotel also has a separate system for accessing the business center (Cognito Identity Pools). Even if you don't have a room key (unauthenticated user), you can get a temporary badge (AWS credentials via IAM roles) that only lets you use the printer (limited permissions). The business center door checks the badge against its own rules (IAM policy attached to the identity pool's role). The hotel keeps a log of all key card issuances and access attempts (Cognito advanced security features, CloudTrail). If someone tries to use a cloned card (token replay), the system can detect anomalies and block access.

How It Actually Works

What is Amazon Cognito?

Amazon Cognito is a fully managed identity service that provides authentication, authorization, and user management for web and mobile applications. It consists of two main components: Cognito User Pools and Cognito Identity Pools (formerly known as Federated Identities).

Cognito User Pools are user directories that handle sign-up, sign-in, and access control. They act as an identity provider (IdP) that issues JSON Web Tokens (JWTs).

Cognito Identity Pools provide temporary AWS credentials for accessing AWS resources (e.g., S3, DynamoDB) based on the identity of a user (authenticated via a user pool or external IdP) or an unauthenticated (guest) user.

The exam expects you to know the difference clearly: User Pools are about *who the user is* (authentication), while Identity Pools are about *what the user can do* (authorization to AWS resources).

How Cognito User Pools Work Internally

When a user signs up in a User Pool, Cognito stores the user profile in a secure directory. The sign-up process can be customized with Lambda triggers (e.g., PreSignUp, PostConfirmation). After sign-up, the user must confirm their account, typically via a verification code sent by email or SMS.

Sign-in (authentication) follows the OAuth 2.0 and OpenID Connect (OIDC) protocols. The user submits credentials to the User Pool's /oauth2/token endpoint (for authorization code grant) or the /login endpoint (for implicit grant). Cognito returns three tokens: - ID token: A JWT containing user claims (e.g., email, phone, custom attributes). Used to identify the user. - Access token: A JWT that authorizes access to User Pool resources (e.g., updating user attributes). It contains scopes and the user's group memberships. - Refresh token: An opaque token (not a JWT) used to obtain new ID and access tokens without re-authentication.

Default token expiry: - Access token: 1 hour (configurable from 5 minutes to 1 day) - ID token: 1 hour (configurable from 5 minutes to 1 day) - Refresh token: 30 days (configurable from 1 day to 3650 days; can be set to never expire)

The tokens are signed using a JSON Web Key Set (JWKS) managed by Cognito. Your application must validate the token's signature, expiry (exp claim), issuer (iss claim), and audience (aud claim for ID token, client_id for access token) by fetching the JWKS from https://cognito-idp.<region>.amazonaws.com/<userPoolId>/.well-known/jwks.json.

Key User Pool Features

Custom attributes: You can define up to 50 custom attributes per user pool. They are read-only after creation.

Password policy: Configurable (minimum length, uppercase, lowercase, numbers, symbols). Default minimum length is 8 characters.

MFA: Supports SMS and time-based one-time password (TOTP) MFA. Can be optional or required.

Account recovery: Email or SMS-based password reset.

Lambda triggers: Pre Sign-up, Post Confirmation, Pre Authentication, Post Authentication, Pre Token Generation, Custom Message, Define Auth Challenge, Create Auth Challenge, Verify Auth Challenge Response, User Migration, and more.

Hosted UI: Cognito provides a default login page that you can customize with a logo and CSS. It supports OAuth 2.0 grants: authorization code, implicit, and client credentials.

App clients: Each User Pool can have multiple app clients (e.g., mobile app, web app) with different settings (e.g., OAuth flows, callback URLs).

Groups: You can create groups and assign IAM roles to them. The group membership is included in the access token as the cognito:groups claim.

Cognito Identity Pools (Federated Identities)

An Identity Pool provides temporary AWS credentials to users. It can authenticate users from:

Cognito User Pools

Public identity providers (Amazon, Apple, Facebook, Google)

OpenID Connect (OIDC) providers

SAML identity providers

Unauthenticated (guest) access

The flow: 1. The user authenticates with an IdP and receives a token. 2. The app exchanges this token for a Cognito identity ID via the GetId API. 3. The app then calls GetCredentialsForIdentity (for authenticated) or GetOpenIdToken (for unauthenticated) to obtain temporary AWS credentials (access key, secret key, session token). 4. These credentials are used to call AWS services (e.g., S3, DynamoDB).

IAM roles: Each Identity Pool has two roles: an authenticated role and an unauthenticated role. You can also define role-based access using IAM policies that reference cognito-identity.amazonaws.com:sub (the identity ID) or cognito-identity.amazonaws.com:aud (the app client ID).

Important: Identity Pools do *not* store user profiles. They only map tokens to AWS credentials. User management (sign-up, sign-in) is handled by the IdP (e.g., User Pool).

Integration with API Gateway

Cognito User Pools can be used as an authorizer for API Gateway REST APIs. When you configure a Cognito User Pool authorizer, API Gateway automatically validates the JWT from the Authorization header. The authorizer checks:

Token signature (using the User Pool's JWKS)

Token expiry

Issuer (must match the User Pool ID)

Audience (must match the app client ID for access tokens; for ID tokens, the audience is the app client ID)

You can also pass the claims to the backend Lambda function via $context.authorizer.claims.

Cognito vs. Lambda authorizer: For fine-grained authorization (e.g., checking user groups, custom logic), use a Lambda authorizer. Cognito authorizer is simpler but only validates the token.

Integration with Application Load Balancer (ALB)

ALB can authenticate users using Cognito User Pools as an OIDC IdP. The ALB acts as an OAuth 2.0 client. When an unauthenticated request arrives, ALB redirects the user to the Cognito Hosted UI. After authentication, Cognito redirects back to ALB with an authorization code. ALB exchanges the code for tokens, validates them, and forwards the user's claims to the target (e.g., EC2, Lambda) via HTTP headers (x-amzn-oidc-accesstoken, x-amzn-oidc-identity, x-amzn-oidc-claims).

Cognito Sync (Deprecated)

Cognito Sync was a service for syncing user data across devices. It is deprecated in favor of AWS AppSync. You do not need to study it for the exam.

Advanced Security Features

Cognito offers advanced security features (paid add-on) that include: - Adaptive authentication: Adjusts MFA requirements based on risk (e.g., new device, location). - Compromised credentials detection: Checks passwords against known leaked credentials. - Audit and logging: Records sign-in attempts, token usage, and user events in CloudTrail and CloudWatch Logs.

Quotas and Limits

Maximum user pools per account: 60 (soft limit, can be increased)

Maximum users per user pool: Unlimited

Maximum groups per user pool: 10,000

Maximum app clients per user pool: 1,000

Maximum identity pools per account: 60

Token size: Max 10 KB for ID and access tokens

Lambda trigger timeout: 5 seconds (Pre Token Generation trigger) or 3 seconds (others)

CLI Commands

Create a user pool:

aws cognito-idp create-user-pool --pool-name MyPool --policies '{"PasswordPolicy":{"MinimumLength":8}}'

Create an app client:

aws cognito-idp create-user-pool-client --user-pool-id us-east-1_abcd1234 --client-name MyApp --no-generate-secret --explicit-auth-flows ALLOW_REFRESH_TOKEN_AUTH

Sign up a user:

aws cognito-idp sign-up --client-id 1234567890abcdef --username johndoe --password P@ssw0rd123

Admin confirm sign-up:

aws cognito-idp admin-confirm-sign-up --user-pool-id us-east-1_abcd1234 --username johndoe

Initiate auth:

aws cognito-idp initiate-auth --auth-flow USER_PASSWORD_AUTH --auth-parameters USERNAME=johndoe,PASSWORD=P@ssw0rd123 --client-id 1234567890abcdef

Verification Commands

Decode a JWT manually (requires jq and base64):

jq -R 'split(".") | .[1] | @base64d | fromjson' <<< "eyJ..."

Fetch JWKS:

curl https://cognito-idp.us-east-1.amazonaws.com/us-east-1_abcd1234/.well-known/jwks.json

Walk-Through

1

User Sign-Up and Confirmation

The user submits registration details (username, password, attributes) to the Cognito User Pool via the `SignUp` API. Cognito creates an unconfirmed user record and triggers a Lambda function if `PreSignUp` trigger is configured. Then, a verification code is sent via email or SMS (depending on attribute verification settings). The user must call `ConfirmSignUp` with the code to activate the account. If `AutoVerifiedAttributes` is set, the user is automatically confirmed upon verification. The `PostConfirmation` Lambda trigger fires after successful confirmation.

2

User Authentication (Sign-In)

The user initiates authentication by calling `InitiateAuth` with `USER_PASSWORD_AUTH` flow (for server-side apps) or `InitiateAuth` with `USER_SRP_AUTH` (for secure SRP protocol). Cognito validates credentials. If MFA is required, Cognito returns a `ChallengeName` of `SMS_MFA` or `SOFTWARE_TOKEN_MFA`. The user must respond with the MFA code via `RespondToAuthChallenge`. On success, Cognito returns ID, access, and refresh tokens. The `PostAuthentication` Lambda trigger executes.

3

Token Issuance and Structure

Cognito issues three tokens: ID token (JWT containing user claims), access token (JWT with scopes and groups), and refresh token (opaque string). The ID and access tokens are signed with the User Pool's private key. The JWKS endpoint exposes the public keys for signature verification. Default token expiry: access and ID tokens 1 hour, refresh token 30 days. The refresh token must be stored securely (e.g., in a secure HTTP-only cookie) and used to obtain new tokens via `AdminInitiateAuth` with `REFRESH_TOKEN_AUTH` flow.

4

Token Validation by Application

The application receives the tokens and must validate them before granting access. Steps: (1) Fetch the JWKS from the User Pool's well-known endpoint. (2) Verify the token signature using the appropriate public key (identified by the `kid` header). (3) Check the `exp` claim (expiration time). (4) Verify the `iss` claim matches the User Pool URL. (5) For ID tokens, verify `aud` matches the app client ID; for access tokens, verify `client_id` matches. (6) Optionally, check `token_use` (id or access). Libraries like `aws-jwt-verify` simplify this.

5

Exchange Tokens for AWS Credentials

To access AWS resources, the app calls Cognito Identity Pools. First, call `GetId` with the login token (e.g., from User Pool) to get a Cognito identity ID. Then, call `GetCredentialsForIdentity` with the identity ID and the login token. Cognito Identity Pool validates the token with the User Pool, assumes the appropriate IAM role (authenticated or unauthenticated, or role based on group), and returns temporary AWS credentials (AccessKeyId, SecretKey, SessionToken, Expiration). These credentials are valid for 1 hour by default (configurable up to 12 hours).

What This Looks Like on the Job

Enterprise Scenario: Mobile App with User Authentication and S3 Access

A company builds a mobile app where users can upload and view photos. They use Cognito User Pools for sign-up/sign-in (including social login via Google) and Cognito Identity Pools to grant temporary AWS credentials for S3 uploads. In production, they configure the User Pool with custom attributes (e.g., preferred_theme) and enable advanced security features to detect compromised credentials. The Identity Pool has an authenticated role with an IAM policy that allows s3:PutObject only to the user's folder (using ${cognito-identity.amazonaws.com:sub} in the resource ARN). They also enable unauthenticated access for browsing public photos with a restricted role. Common issues: Users sometimes get 'AccessDenied' errors because the Identity Pool's role trust policy doesn't include the User Pool as an authentication provider. The fix is to ensure the 'Authentication providers' section of the Identity Pool includes the User Pool ID. Performance is not a concern as Cognito handles millions of users; however, token validation on every request can be CPU-intensive on the client, so they cache the JWKS for 1 hour.

Enterprise Scenario: Serverless Web App with API Gateway and Cognito Authorizer

A SaaS company builds a serverless web app using Lambda and API Gateway. They use Cognito User Pools as the authorizer. When a user logs in via the Hosted UI, they receive tokens. The frontend sends the access token in the Authorization header. API Gateway's Cognito authorizer validates the token automatically. The backend Lambda receives user claims via $context.authorizer.claims and uses them for fine-grained authorization (e.g., checking cognito:groups). They use groups to separate free and premium users. The premium group has an IAM role that allows access to premium DynamoDB tables. A common pitfall: The token's aud claim must match the API Gateway's client ID; if the app client is used for multiple purposes, the token may be rejected. They also set a short access token expiry (15 minutes) and use refresh tokens to renew them. Misconfiguration: If the User Pool's token validity is too long, a revoked user can still access resources until the token expires.

Enterprise Scenario: ALB Authentication with Cognito

A company hosts a legacy web app behind an Application Load Balancer. They want to add authentication without modifying the app. They configure ALB to authenticate users via Cognito User Pool using OIDC. When users visit the site, ALB redirects them to the Cognito Hosted UI. After login, Cognito redirects back to ALB with an authorization code. ALB exchanges the code for tokens, validates them, and forwards user claims to the backend in HTTP headers. The backend reads x-amzn-oidc-claims (base64-encoded JSON) to get user info. They configure a session cookie (cookie name AWSELBAuthSessionCookie) with a configurable timeout (default 1 day). A common issue: The backend must validate the x-amzn-oidc-accesstoken if it needs to call AWS services on behalf of the user. They also set up a custom domain for the Hosted UI to match their brand. At scale, the ALB handles token validation efficiently, but the Cognito User Pool must be in the same region as the ALB.

How DVA-C02 Actually Tests This

DVA-C02 Exam Focus on Amazon Cognito

The DVA-C02 exam tests Cognito under Domain 2: Security, Objective 2.2: *Implement authentication and authorization for applications*. You must be able to:

Differentiate between Cognito User Pools and Identity Pools.

Understand token flow (ID, access, refresh tokens).

Configure API Gateway Cognito authorizer.

Integrate Cognito with ALB.

Implement federation with social IdPs and SAML.

Use Lambda triggers (especially Pre Token Generation for customizing claims).

Understand how Identity Pools grant AWS credentials.

Common Wrong Answers and Traps

1.

Confusing User Pools with Identity Pools: A question might ask: 'Which Cognito component provides temporary AWS credentials?' The wrong answer is 'User Pool' because it sounds like it handles identity. But User Pools only authenticate; Identity Pools grant credentials.

2.

Assuming tokens are always valid: Candidates think that if a token is present, it's valid. The exam tests that tokens must be validated (signature, expiry, issuer, audience). A common distractor is 'Use the token as-is because Cognito already validated it.'

3.

Wrong token for authorizer: API Gateway Cognito authorizer expects the access token, not the ID token. However, if you use the ID token, it may work if the audience matches. The exam may ask: 'Which token should be used in the Authorization header?' The correct answer is the access token.

4.

Forgetting refresh token expiry: Refresh tokens have a default expiry of 30 days. A question might say 'The user is still active but cannot get new tokens after 30 days.' The answer is to adjust the refresh token validity or implement a new sign-in.

5.

Lambda trigger confusion: The Pre Token Generation trigger can add custom claims to the ID and access tokens. A question might ask which trigger to use to add user attributes to the token. The correct answer is Pre Token Generation.

Specific Numbers and Values

Default access/ID token expiry: 1 hour

Default refresh token expiry: 30 days

Max custom attributes: 50

Max user pools per account: 60

Lambda trigger timeout: 5 seconds (Pre Token Generation), 3 seconds (others)

Identity Pool credentials default duration: 1 hour (max 12 hours)

JWKS endpoint: https://cognito-idp.<region>.amazonaws.com/<userPoolId>/.well-known/jwks.json

Edge Cases

Token replay: If a token is stolen, it can be used until expiry. Cognito does not have built-in token revocation except by changing the User Pool's signing key (which invalidates all tokens). Advanced security features can detect anomalous token usage.

Unconfirmed users: A user who signs up but does not confirm cannot authenticate. The exam may ask how to allow immediate access: use AdminConfirmSignUp or set AutoVerifiedAttributes.

Custom scopes: You can define custom scopes for resource servers. The exam may ask how to limit access to specific API endpoints.

How to Eliminate Wrong Answers

If the question mentions 'AWS credentials', the answer must involve Identity Pools.

If the question mentions 'sign-up', 'sign-in', 'user directory', the answer is User Pools.

If the question mentions 'API Gateway authorizer', think of Cognito User Pools or Lambda authorizer.

If the question mentions 'federation with Facebook', the answer is User Pools (social IdP) or Identity Pools (federated identities).

Always check the token type: access token for API Gateway, ID token for user identification.

Key Takeaways

Cognito User Pools authenticate users and issue JWTs; Identity Pools grant AWS credentials.

Default token expiry: access/ID tokens = 1 hour; refresh token = 30 days.

API Gateway Cognito authorizer validates the access token's signature, expiry, issuer, and audience.

Use Pre Token Generation Lambda trigger to add custom claims to tokens.

Identity Pool credentials default duration is 1 hour (max 12 hours).

JWKS endpoint: https://cognito-idp.<region>.amazonaws.com/<userPoolId>/.well-known/jwks.json

Cognito supports MFA via SMS and TOTP.

Maximum 60 user pools per AWS account (soft limit).

Easy to Mix Up

These come up on the exam all the time. Here's how to tell them apart.

Cognito User Pools

Provides user authentication (sign-up, sign-in)

Issues JWTs (ID, access, refresh tokens)

Stores user profiles and attributes

Integrates with social IdPs and SAML

Can be used as API Gateway authorizer

Cognito Identity Pools

Provides temporary AWS credentials

Exchanges tokens from IdPs for AWS credentials

Does not store user profiles

Supports unauthenticated (guest) access

Requires an IdP (User Pool, social, SAML) or unauthenticated

Watch Out for These

Mistake

Cognito User Pools can grant direct access to AWS resources like S3.

Correct

User Pools only authenticate users and issue JWTs. To access AWS resources, you must use Cognito Identity Pools to exchange the JWT for temporary AWS credentials.

Mistake

Cognito tokens are opaque and cannot be decoded.

Correct

ID and access tokens are JSON Web Tokens (JWTs) that are base64-encoded JSON. They can be decoded to view claims, but the signature must be verified using the User Pool's public key.

Mistake

API Gateway Cognito authorizer validates the ID token by default.

Correct

The Cognito authorizer expects the access token in the Authorization header. The ID token can be used if the audience matches the app client ID, but the recommended token is the access token.

Mistake

Refresh tokens never expire.

Correct

Refresh tokens have a configurable expiration, defaulting to 30 days. They can be set to never expire (up to 3650 days), but the default is finite.

Mistake

Cognito Identity Pools require a User Pool to function.

Correct

Identity Pools can work with any OIDC or SAML identity provider, including social IdPs (Google, Facebook) and even unauthenticated (guest) access. A User Pool is just one option.

Do You Actually Know This?

Reveal each answer, then mark whether you got it right. Score 60%+ to unlock the next chapter.

Frequently Asked Questions

What is the difference between Cognito User Pools and Identity Pools?

Cognito User Pools are user directories that handle authentication (sign-up, sign-in) and issue JWTs. Cognito Identity Pools provide temporary AWS credentials (access keys, secret keys, session tokens) to access AWS services like S3 or DynamoDB. User Pools answer 'who are you?'; Identity Pools answer 'what can you do?'.

How do I validate a Cognito JWT in my application?

Fetch the JWKS from the User Pool's well-known endpoint, verify the token signature using the appropriate public key, check the `exp` claim, verify `iss` matches your User Pool URL, and ensure `aud` (for ID tokens) or `client_id` (for access tokens) matches your app client ID. Use libraries like `aws-jwt-verify` (Node.js) or `cognito-jwt-verifier` (Python).

Can I use Cognito with an Application Load Balancer?

Yes. ALB can authenticate users using Cognito User Pools as an OIDC IdP. When a user is not authenticated, ALB redirects them to the Cognito Hosted UI. After login, Cognito redirects back to ALB, which exchanges the authorization code for tokens and forwards user claims to the backend via HTTP headers.

How do I add custom claims to a Cognito token?

Use the Pre Token Generation Lambda trigger. This trigger fires before token issuance and allows you to modify the ID and access tokens by adding, removing, or overriding claims. The Lambda receives the current token's claims and the user's attributes and returns the modified claims.

What is the default expiry for Cognito tokens?

Access and ID tokens default to 1 hour (configurable from 5 minutes to 1 day). Refresh tokens default to 30 days (configurable from 1 day to 3650 days, or can be set to never expire).

How do I grant a user access to a specific S3 bucket using Cognito?

Use Cognito Identity Pools. After the user authenticates (e.g., via User Pool), exchange the token for temporary AWS credentials via `GetCredentialsForIdentity`. In the Identity Pool's IAM role, define a policy that restricts access to the user's folder using the `cognito-identity.amazonaws.com:sub` condition key.

Can I use Cognito without a User Pool for unauthenticated access?

Yes. Cognito Identity Pools support unauthenticated (guest) identities. You can enable 'Enable access to unauthenticated identities' in the Identity Pool. Unauthenticated users get a unique identity ID and temporary AWS credentials with limited permissions defined in the unauthenticated IAM role.

Terms Worth Knowing

Ready to put this to the test?

You've just covered Amazon Cognito — now see how well it sticks with free DVA-C02 practice questions. Full explanations included, no account needed.

Done with this chapter?