8.2 Amazon Cognito User Pools & Identity Pools

Key Takeaways

  • Amazon Cognito User Pools act as an identity provider and user directory handling registration, authentication, and directory management, outputting OIDC-compliant JWT tokens (ID, Access, and Refresh tokens).

  • Amazon Cognito Identity Pools (Federated Identities) act as an authorization broker, exchanging external identity tokens from User Pools, social providers, SAML, or OIDC for temporary AWS STS credentials.

  • User pool threat protection (formerly advanced security features, in the Plus plan) defends against credential stuffing and account takeover with compromised-credential detection and adaptive, risk-based authentication.

  • Cognito Lambda triggers inject serverless logic across authentication lifecycle stages, enabling token enrichment, dynamic claim insertion, custom challenge workflows, and third-party risk verification.

  • Identity Pools resolve IAM roles for authenticated and unauthenticated guest users through default mappings, rules-based claim matching, or token-based group associations.

Last updated: September 2026

8.2 Amazon Cognito User Pools & Identity Pools

Modern cloud-native and mobile applications require scalable identity architectures that can support millions of users, social logins, multi-factor authentication, and secure access to backend AWS services without embedding long-term credentials in client applications. Amazon Cognito addresses these requirements through two distinct architectural primitives: Cognito User Pools and Cognito Identity Pools (Federated Identities).

A mastery of the separation of responsibilities between User Pools (authentication) and Identity Pools (authorization), token validation mechanics, threat protection, Lambda trigger customization, and fine-grained STS credential vending is critical for the AWS Certified Security – Specialty exam.


Architectural Separation: User Pools vs. Identity Pools

The fundamental architectural distinction between User Pools and Identity Pools frequently appears on the exam:

User Pools = Authentication ("Who you are")  -->  Outputs OIDC JSON Web Tokens (JWTs)
Identity Pools = Authorization ("What you can do")  -->  Vends Temporary AWS IAM Credentials (STS)
Architectural DimensionAmazon Cognito User PoolsAmazon Cognito Identity Pools
Primary FunctionIdentity Provider (IdP) & user directory service.Identity broker & authorization credential vending service.
Core CapabilitiesUser sign-up, sign-in, password reset, hosted UI, MFA, adaptive risk profiling.Exchanges external identity tokens for temporary AWS IAM credentials via AWS STS.
Supported Identity SourcesBuilt-in directory, social providers (Google, Apple, Facebook), SAML 2.0 IdPs, OIDC IdPs.Cognito User Pools, OpenID Connect (OIDC) providers, SAML 2.0 IdPs, Public Social IdPs, Unauthenticated Guests.
Output ArtifactsStandard OIDC JSON Web Tokens (ID Token, Access Token, Refresh Token).Temporary AWS credentials (AccessKeyId, SecretAccessKey, SessionToken, Expiration).
Target ConsumptionApplication frontends, API Gateway Cognito Authorizers, ALB OIDC listeners.Direct client SDK access to AWS services (e.g., Amazon S3, Amazon DynamoDB, Amazon AppSync).
Loading diagram...

Amazon Cognito User Pools: Directory & JWT Architecture

A User Pool is an enterprise-scale user directory that handles user registration, attribute storage, credential verification, and session management. It can be integrated using the AWS-managed Cognito Hosted UI (an out-of-box OAuth 2.0 / OIDC login interface) or via custom application interfaces using the AWS Amplify SDK or AWS SDKs.

OIDC JSON Web Tokens (JWT) Deep Dive

Upon successful authentication, a Cognito User Pool issues three standard JSON Web Tokens. Each token serves a specialized architectural purpose:

  1. ID Token (Identity Proof):
    • Purpose: Proves the identity of the authenticated user to the client application and Identity Pools.
    • Key Claims: Contains identity attributes such as sub (unique user UUID), email, cognito:groups, aud (app client ID), iss (User Pool issuer URL), and custom user attributes.
    • Format: Signed using RS256 (RSA Signature with SHA-256). Can be exchanged with Cognito Identity Pools to obtain AWS credentials.
  2. Access Token (API Authorization):
    • Purpose: Authorizes calls to protected API endpoints, such as Amazon API Gateway REST/HTTP APIs or custom microservices.
    • Key Claims: Contains authorization scopes (scope), client_id, username, and cognito:groups. It does not contain sensitive user identity claims (like email or phone number).
    • Target: Validated by API Gateway Cognito Authorizers to authorize or deny API requests based on OAuth scopes.
  3. Refresh Token (Session Maintenance):
    • Purpose: Obtains fresh ID and Access tokens without requiring the user to re-enter their password.
    • Expiration: Configurable from 60 minutes to 10 years (default is 30 days).
    • Refresh Token Rotation: When enabled on the app client, each refresh returns a new refresh token and invalidates the original (after an optional grace period of up to 60 seconds), limiting replay of an intercepted token. Rotation requires the GetTokensFromRefreshToken API; the REFRESH_TOKEN_AUTH flow must be disabled.

Validating Cognito JWT Tokens

When a backend service receives a JWT from a client, it must validate the token offline without calling the Cognito API for every request:

  • Verify Signature: Fetch the public JSON Web Key Set (JWKS) from https://cognito-idp.<region>.amazonaws.com/<userPoolId>/.well-known/jwks.json. Match the kid (Key ID) header in the JWT with the corresponding public key in the JWKS and verify the cryptographic signature.
  • Verify Issuer (iss): Confirm the iss claim exactly matches https://cognito-idp.<region>.amazonaws.com/<userPoolId>.
  • Verify Audience (aud): For ID tokens, confirm the aud claim matches the application's Cognito App Client ID. For Access tokens, verify the client_id.
  • Verify Expiration (exp): Confirm the token has not expired (exp > current epoch time).

Threat Protection & Adaptive Authentication

For threat mitigation, Cognito user pools provide threat protection (called advanced security features before the November 2024 feature plans; now part of the Plus plan). It evaluates sign-in risk and checks passwords against leaked-credential data to detect and prevent account takeover.

Operating Modes

  • Audit Only: Logs suspicious activities, credential stuffing attempts, and risk evaluations to Amazon CloudWatch without interfering with user login attempts. Used to baseline application traffic.
  • Enforce: Automatically initiates defensive challenges or blocks sign-in based on calculated risk scores.

Core Security Defenses

  1. Compromised Credential Checks (Leaked Credential Detection):
    • Cognito compares submitted passwords with credentials from public data breaches and with commonly guessed passwords. Detection works for username-and-password flows, not for SRP or custom authentication flows.
    • If a user attempts to sign up, sign in, or reset their password using compromised credentials, Cognito can automatically prompt the user to change their password or block the request.
  2. Adaptive Authentication (Risk-Based Step-Up):
    • Cognito calculates a dynamic risk level (Low, Medium, or High) for each authentication attempt by evaluating contextual signals: source IP address, geolocation, device fingerprint, operating system, and time of day.
    • Action Configuration: Administrators configure responses based on risk severity:
      • Low Risk: Allow sign-in without additional friction.
      • Medium Risk: Prompt for second-factor authentication (SMS or TOTP MFA).
      • High Risk: Block the sign-in attempt entirely or require step-up MFA and send an automated notification to the user's verified email.
Loading diagram...

Cognito Lambda Triggers: Intercepting the Auth Lifecycle

Cognito allows security teams to inject custom serverless logic into the authentication flow via AWS Lambda triggers. Lambda triggers execute synchronously or asynchronously at predefined extension points:

Loading diagram...

Critical Security Triggers for the Exam

  • Pre Sign-Up: Validates user attributes before account creation. Used to enforce corporate domain restrictions (e.g., rejecting any sign-up where the email does not end in @example.com) or automatically verifying trusted attributes.
  • Pre Authentication: Executes before credential validation. Used to enforce custom IP CIDR allowlists, geo-blocking, or rate-limiting fraud attempts before Cognito checks the user's password.
  • Pre Token Generation (Crucial for Authorization):
    • Executes immediately before Cognito signs and issues the ID token.
    • Capability: Allows the Lambda function to dynamically add, modify, or suppress claims in the ID token. For example, the function can query an internal database and inject custom authorization claims, such as "tenant_id": "corp-102" or dynamic group roles, which downstream microservices and Identity Pools use for access control.
  • Custom Authentication Challenges (SRP / Passwordless):
    • Combines three triggers: Define Auth Challenge, Create Auth Challenge, and Verify Auth Challenge Response.
    • Used to implement passwordless authentication, CAPTCHA validation, or custom SMS/email one-time verification workflows.

Amazon Cognito Identity Pools: Federated Credential Vending

While User Pools issue JWTs, AWS APIs do not accept JWTs directly (with the exception of API Gateway). To interact with services like Amazon S3, Amazon DynamoDB, or AWS KMS, a client application requires AWS credentials signed with Signature Version 4 (SigV4).

Amazon Cognito Identity Pools act as an exchange broker, accepting authenticated identity tokens from diverse providers and vending temporary, short-lived AWS IAM credentials via AWS STS.

Supported Identity Providers in Identity Pools

  1. Amazon Cognito User Pools (passing the User Pool ID token).
  2. Public Social IdPs: Google, Apple, Facebook, Amazon.
  3. OpenID Connect (OIDC) Providers: Any standard OIDC-compliant identity system (e.g., Salesforce, Auth0).
  4. SAML 2.0 Identity Providers: Enterprise federations (e.g., Okta, PingFederate).
  5. Developer Authenticated Identities: Custom backend systems vending tokens using the GetOpenIdTokenForDeveloperIdentity API.
  6. Unauthenticated (Guest) Access: Issues temporary AWS credentials to anonymous users without requiring any sign-in (e.g., allowing guest users to download preview assets from an S3 bucket).

The Identity Pool Exchange Sequence

  1. The client presents an identity token (e.g., a Cognito User Pool ID token) to the Identity Pool via the GetId API to obtain an IdentityId (a unique identifier for the user in the format <region>:<uuid>).
  2. The client calls GetCredentialsForIdentity, passing the token and IdentityId.
  3. The Identity Pool validates the token signature, issuer, and expiration.
  4. The Identity Pool invokes STS AssumeRoleWithWebIdentity on behalf of the user, passing the configured IAM role ARN.
  5. STS returns temporary AWS credentials (AccessKeyId, SecretAccessKey, SessionToken, Expiration) to the Identity Pool, which returns them to the client application.

Role Resolution & Fine-Grained Authorization

Identity Pools determine which IAM role to assign to a user through three distinct role resolution mechanisms:

  1. Default Authenticated / Unauthenticated Roles: A baseline IAM role assigned to all authenticated users, and a separate locked-down role assigned to guest users.
  2. Rules-Based Role Mapping: Evaluates user claims within the incoming token using conditional logic. For example: If claim "department" equals "SecurityOperations", assign Role "arn:aws:iam::123456789012:role/SecOpsRole".
  3. Token-Based Group Mapping: Automatically maps the user's cognito:groups claim in their User Pool token directly to specific IAM role ARNs configured on the Cognito User Pool group.

Fine-Grained Resource Access Control (FGAC) with IAM Policy Variables

To prevent users from accessing other users' private data without creating individual IAM roles for every user, Identity Pools leverage IAM Policy Variables based on the Cognito identity ID (${cognito-identity.amazonaws.com:sub}):

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AllowUserSpecificS3FolderAccess",
      "Effect": "Allow",
      "Action": [
        "s3:GetObject",
        "s3:PutObject",
        "s3:DeleteObject"
      ],
      "Resource": "arn:aws:s3:::enterprise-user-storage/${cognito-identity.amazonaws.com:sub}/*"
    },
    {
      "Sid": "AllowListOnlyUserFolder",
      "Effect": "Allow",
      "Action": "s3:ListBucket",
      "Resource": "arn:aws:s3:::enterprise-user-storage",
      "Condition": {
        "StringLike": {
          "s3:prefix": ["${cognito-identity.amazonaws.com:sub}/*"]
        }
      }
    }
  ]
}

In this policy, whenever a user assumes the role, AWS STS dynamically evaluates ${cognito-identity.amazonaws.com:sub} to the user's actual Cognito Identity ID (e.g., us-east-1:1a2b3c4d-5e6f-7a8b-9c0d-1e2f3a4b5c6d). This guarantees strict user folder isolation in Amazon S3 using a single shared IAM role.


Specialty Exam Pitfalls & Architectural Traps

  1. Direct AWS Access via User Pool Alone: A frequent architectural mistake is assuming that a client with a Cognito User Pool ID token or Access token can call Amazon S3 or DynamoDB directly. User Pools produce JWTs, not AWS credentials. Clients must exchange the JWT through a Cognito Identity Pool to obtain SigV4-compatible STS temporary credentials.
  2. ID Token vs. Access Token Validation: When integrating with Amazon API Gateway, the Cognito Authorizer validates the token. If authorization is based on OAuth scopes, you must pass the Access Token. If the authorizer or downstream service expects identity claims (e.g., email, sub), passing an Access token will result in missing claims because identity claims exist only in the ID Token.
  3. Client Secrets in Public Applications: When creating a Cognito App Client for Single-Page Web Applications (SPAs) or mobile apps, never generate a client secret. Public clients cannot securely store cryptographic secrets. Including a client secret in a browser or mobile app exposes the secret to reverse engineering and causes API calls that lack the SECRET_HASH parameter to fail.
  4. Offline Token Verification without JWKS: Backend microservices verifying Cognito JWTs must not make an HTTP request to Cognito on every incoming call. Doing so introduces severe latency and triggers API rate limits. Microservices must cache the public keys from the Cognito .well-known/jwks.json endpoint and perform local cryptographic signature verification.
Loading diagram...
Amazon Cognito End-to-End Authentication & Scoped AWS Resource Authorization
Test Your Knowledge

A mobile healthcare application requires patients to sign up, sign in with multi-factor authentication, and upload medical diagnostic images directly from their mobile devices into a private Amazon S3 bucket. Patients must be strictly isolated so they can only access their own uploaded images. The architecture must minimize server management and avoid routing file uploads through an intermediate application server. Which architectural pattern fulfills these requirements?

A

Use a Cognito User Pool for user authentication, exchange the resulting ID token with a Cognito Identity Pool to vend temporary AWS STS credentials, and attach an IAM role policy that restricts S3 object access using the ${cognito-identity.amazonaws.com:sub} policy variable.

B

Use a Cognito Identity Pool to manage patient passwords and registration, and configure an IAM policy with the ${aws:username} policy variable attached to an IAM group.

C

Use a Cognito User Pool to issue JWT tokens, configure an API Gateway Cognito Authorizer, and route all file uploads as binary payloads through an AWS Lambda function that writes to S3.

D

Create a single long-term IAM user with AmazonS3FullAccess, embed the access keys within the mobile application package, and partition user uploads using local client folder names.

Test Your Knowledge

A financial SaaS platform uses Amazon Cognito User Pools to manage client identities. Downstream microservices deployed in Amazon ECS require an authorization claim named 'tenant_tier' (e.g., 'Gold', 'Silver', 'Standard') inside the JWT token to enforce rate limits and feature entitlements. The tenant tier is stored in an internal Amazon DynamoDB table and updated dynamically by the billing department. How can the security team ensure that every issued ID token contains the current 'tenant_tier' claim without altering the client application sign-in code?

A

Configure a Post Confirmation Lambda trigger to write the tenant tier into the user's custom attributes in Cognito every time the user signs up.

B

Require the client application to query DynamoDB directly, attach the tenant tier to the HTTP request headers, and pass it to downstream services.

C

Configure a Pre Token Generation Lambda trigger that queries DynamoDB for the user's current tenant tier and dynamically injects the 'tenant_tier' claim into the ID token claims override map before the token is signed.

D

Create an Amazon EventBridge rule on Cognito sign-in events that updates the Cognito App Client configuration with new tenant scopes.

Test Your Knowledge

An enterprise backend microservice written in Go runs behind a Network Load Balancer and receives incoming HTTP requests carrying Amazon Cognito User Pool JWT tokens in the Authorization header. To maintain high throughput and low latency, the microservice must validate the tokens locally. Which set of validation steps must the microservice perform?

A

Send an HTTP POST request with the token to the Cognito UserPool Auth endpoint for every request to verify validity.

B

Download and cache the public JSON Web Key Set (JWKS) from Cognito's .well-known/jwks.json endpoint, verify the RS256 signature using the matching key ID (kid), and validate that the iss, aud, and exp claims match expected values.

C

Decrypt the token using the KMS AWS-managed key associated with the Cognito User Pool and inspect the token expiration timestamp.

D

Extract the base64-encoded payload from the JWT, deserialize the JSON string, and verify that the exp claim is greater than the current system time without verifying the signature.

Test Your Knowledge

A retail organization experiences automated credential-stuffing attacks against its consumer web application hosted on Amazon Cognito User Pools. The security team must immediately implement automated detection to block login attempts originating from compromised credentials that have been exposed in third-party data breaches, while prompting legitimate users for step-up multi-factor authentication if their login patterns deviate significantly from normal baselines. Which configuration satisfies this requirement with the least operational overhead?

A

Deploy AWS WAF with rate-based rules and custom regex pattern matching to analyze login request payloads.

B

Create an AWS Lambda trigger on Pre Authentication that queries the HaveIBeenPwned API and computes IP geolocation risk.

C

Export Cognito user sign-in logs to Amazon OpenSearch Service and write automated alerting alerts to disable compromised users via the AWS CLI.

D

Move the user pool to the Plus feature plan, turn on threat protection in full-function (enforce) mode, block sign-ins and sign-ups that use compromised credentials, and configure adaptive authentication to require MFA for medium-risk and block high-risk sign-ins.

Sections you finish are checked off in the contents.