Prev Next

Cloud / Amazon Cognito Interview questions

Last updated

1. What is Amazon Cognito? 2. What are the main components of Amazon Cognito? 3. What is an Amazon Cognito user pool? 4. What is an Amazon Cognito identity pool? 5. What is the difference between a user pool and an identity pool? 6. What is a Cognito app client? 7. What are the tokens issued by a Cognito user pool? 8. What is the refresh token used for in Cognito? 9. What is the Cognito hosted UI? 10. What are standard and custom attributes in Cognito? 11. What are the sign-in options in a Cognito user pool? 12. How do you enable MFA in a Cognito user pool? 13. What are user pool groups in Cognito? 14. What identity providers can you federate with in Cognito? 15. What is guest access in Cognito identity pools? 16. What are the password policy settings in Cognito? 17. What is a Cognito domain? 18. What is the pricing model of Amazon Cognito? 19. How do you integrate Cognito with a web or mobile app? 20. What are the user statuses in a Cognito user pool? 21. How does the Cognito user pool authentication flow work? 22. What is the difference between a Cognito ID token and an access token? 23. What OAuth 2.0 grant types does Cognito support? 24. Why should you use the authorization code grant with PKCE in Cognito? 25. How does Cognito integrate with API Gateway? 26. How does an Application Load Balancer authenticate users with Cognito? 27. How does an identity pool issue temporary AWS credentials? 28. What is the difference between enhanced and basic authflow in identity pools? 29. How do you validate a Cognito JWT on the backend? 30. What are Lambda triggers in Cognito? 31. What is the Pre Token Generation trigger used for? 32. When would you use the Pre sign-up Lambda trigger? 33. How do custom authentication challenges work in Cognito? 34. How do you revoke Cognito tokens? 35. How does role-based access control work in identity pools? 36. How do you use attribute-based access control with Cognito? 37. How do you configure SAML federation in Cognito? 38. How do you link federated users to existing user pool accounts? 39. How do you migrate existing users into Cognito? 40. How does adaptive authentication work in Cognito? 41. How do you handle Cognito API throttling? 42. How do you protect a Cognito user pool with AWS WAF? 43. How do you customize Cognito emails and SMS messages? 44. How do you troubleshoot a redirect_mismatch error in Cognito? 45. What are resource servers and custom scopes in Cognito? 46. How do you implement machine-to-machine authentication with Cognito? 47. How would you design multi-tenancy with Cognito? 48. When would you choose Cognito over a third-party identity provider? 49. How should you store Cognito tokens in a browser app? 50. How do you monitor and audit Cognito activity?

1. What is Amazon Cognito?

Amazon Cognito is an AWS service that handles sign-up, sign-in, and access control for web and mobile applications. It is AWS's customer identity and access management (CIAM) offering, so you don't have to build and secure your own login system.

It has two core building blocks. User pools are user directories that authenticate people and issue JSON Web Tokens (JWTs). Identity pools exchange a verified identity for temporary AWS credentials so the app can call services like S3 or DynamoDB directly.

Cognito also supports social and enterprise federation (Google, Apple, SAML, OIDC), multi-factor authentication, and Lambda triggers for customizing the flow.

Take quiz
Which Cognito component issues JWTs after a user signs in?
Identity pool
Cognito Sync store
IAM role trust policy
User pool
Amazon Cognito is best described as:
a managed relational database
a customer identity and access management service
a CDN for static sign-in pages
an AWS billing and cost tool

2. What are the main components of Amazon Cognito?

Cognito has two main components: user pools and identity pools. Most applications use one or both.

  • User pool - a user directory that handles registration, sign-in, MFA, password recovery, and token issuance.
  • Identity pool (federated identities) - maps authenticated or guest users to IAM roles and returns temporary AWS credentials.

Around these sit supporting pieces: app clients, the hosted UI (managed login), Lambda triggers, groups, and identity provider configurations. Cognito Sync, an older dataset-sync feature, is legacy and AWS AppSync is recommended instead.

Take quiz
Which pair makes up the two core Cognito components?
User pools and identity pools
Directories and vaults
App clients and API keys
Roles and policies
Which component returns temporary AWS credentials?
User pool group
App client secret
Identity pool
Hosted UI domain

3. What is an Amazon Cognito user pool?

A user pool is a managed user directory in Cognito. It stores user profiles and handles the whole authentication lifecycle: sign-up, email or phone verification, sign-in, MFA, password reset, and account recovery.

After a successful sign-in the pool issues an ID token, an access token, and a refresh token. Your backend can verify the JWTs without calling Cognito on every request.

A user pool can also act as an OIDC provider for your apps and as a broker for external identity providers such as Google, Facebook, Apple, SAML, and OIDC.

Take quiz
What does a user pool return after successful authentication?
Only an IAM access key pair
A signed S3 URL
ID, access, and refresh tokens
A VPC endpoint address
A user pool is primarily a:
user directory with authentication features
storage bucket for user files
DNS zone for login domains
logging pipeline for CloudTrail

4. What is an Amazon Cognito identity pool?

An identity pool (also called federated identities) gives users temporary AWS credentials. It takes proof of identity from a trusted source - a Cognito user pool, a social provider, a SAML or OIDC provider, or even no login at all - and trades it for short-lived credentials through AWS STS.

Each identity pool is linked to IAM roles, typically one for authenticated users and one for guests. The role's policy decides what AWS resources the user can touch.

This is how a mobile app can upload straight to S3 without routing the file through your servers.

Take quiz
What is the main output of an identity pool?
A signed JWT for your API only
A permanent IAM user
A CloudFront cookie
Temporary AWS credentials
What controls what a user can do with identity pool credentials?
The user pool password policy
The IAM role attached to the identity
The app client callback URL
The Cognito domain prefix

5. What is the difference between a user pool and an identity pool?

A user pool answers "who are you?" (authentication). An identity pool answers "what AWS resources may you use?" (authorization to AWS services).

Feature User pool Identity pool
Purpose Authenticate users Grant AWS access
Output JWT tokens Temporary AWS credentials
Stores users Yes, a directory No, only identity mappings
Guest access No Yes, unauthenticated identities
Typical consumer Your APIs and app AWS SDK calls from the client

They work best together: sign in with the user pool, then hand the ID token to the identity pool to get AWS credentials. If your app only calls your own API, a user pool alone is enough.

Take quiz
You only need to secure your own REST API with logins. Which do you need?
A user pool
Only an identity pool
Cognito Sync
An IAM user per customer
Which one supports guest (unauthenticated) access to AWS resources?
User pool
App client
Identity pool
Resource server

6. What is a Cognito app client?

An app client is a registered application inside a user pool. It has a client ID and, optionally, a client secret, and it defines how that specific app is allowed to talk to the pool.

Settings live at the client level: allowed auth flows (for example ALLOW_USER_SRP_AUTH), OAuth grant types and scopes, callback and logout URLs, token lifetimes, and which attributes the app can read or write.

Use a secret only for confidential, server-side clients. Browser and mobile apps are public clients and should not have one, since the secret cannot be kept hidden. The secret can't be added after the client is created.

Take quiz
Which app type should NOT use a client secret?
A server-side web app
A backend service using client credentials
A single-page application running in the browser
A confidential API worker
Where do you configure callback URLs and token lifetimes?
On the app client
On the identity pool role
In the SES sending profile
On the Lambda execution role

7. What are the tokens issued by a Cognito user pool?

A user pool issues three tokens after authentication:

  • ID token - a JWT with identity claims such as sub, email, and custom attributes. Used by your app to know who signed in.
  • Access token - a JWT used to authorize API calls. It carries scopes and group membership, not profile details.
  • Refresh token - an opaque, encrypted token used to get new ID and access tokens without asking the user to sign in again.

By default ID and access tokens last 1 hour (configurable from 5 minutes to 1 day) and the refresh token lasts 30 days (configurable from 60 minutes to 10 years).

Take quiz
Which Cognito token is NOT a JWT?
ID token
Access token
None, all three are JWTs
Refresh token
What is the default lifetime of ID and access tokens?
5 minutes
1 hour
24 hours
30 days

8. What is the refresh token used for in Cognito?

The refresh token lets an app get fresh ID and access tokens after they expire, without prompting the user for credentials again. You can send it to the token endpoint with grant_type=refresh_token or use the GetTokensFromRefreshToken API.

By default the original refresh token stays valid and only new ID and access tokens come back. If you enable refresh token rotation on the app client, each refresh also returns a new refresh token and the old one is invalidated, with an optional grace period of up to 60 seconds for retries.

When the refresh token itself expires or is revoked, the user has to sign in again.

Take quiz
What does a normal refresh request return when rotation is off?
New ID and access tokens; the refresh token stays valid
A new refresh token only
Temporary IAM credentials
A new user pool ID
What happens once the refresh token expires?
Cognito silently extends it forever
The access token becomes permanent
The user must authenticate again
The app client is deleted

9. What is the Cognito hosted UI?

The hosted UI is a ready-made sign-in and sign-up web experience served by Cognito on your user pool domain. Newer console versions call the customizable version managed login.

Your app redirects the user to it, they authenticate (including social or SAML sign-in and MFA), and Cognito redirects back to a registered callback URL with an authorization code or tokens.

It saves you from building login screens and handles the OAuth 2.0 and OIDC endpoints for you. You can brand it with logos, colors, and CSS, or with the managed login editor, and put it behind a custom domain.

Take quiz
How does the hosted UI return the user to your app?
It emails the tokens
It writes tokens to S3
It redirects to a registered callback URL
It calls your Lambda authorizer directly
What is the main benefit of the hosted UI?
You don't have to build the login pages yourself
It removes the need for an app client
It replaces IAM roles
It stores files for users

10. What are standard and custom attributes in Cognito?

Standard attributes are the OIDC-defined profile fields Cognito ships with, such as email, phone_number, name, and birthdate. Custom attributes are ones you define yourself, and Cognito stores them with the prefix custom:, for example custom:tenantId.

  • Custom attributes can be strings or numbers, and you can add them after the pool exists.
  • You can't delete or rename a custom attribute once created, and you can't change its data type.
  • Mutability matters: a non-mutable attribute can only be set at sign-up.
  • Required standard attributes must be chosen at pool creation.
Take quiz
How does Cognito name a custom attribute called plan?
x-plan
plan_custom
attr.plan
custom:plan
Which change is NOT possible for an existing custom attribute?
Reading it in the ID token
Deleting it
Setting its value for a user
Mapping it from an IdP

11. What are the sign-in options in a Cognito user pool?

You choose how users identify themselves when creating the pool. The options are username, or email address, phone number, or both as username attributes, which lets users sign in with those values.

If you use username attributes, Cognito generates an internal username (a UUID-style value) and the email or phone becomes the login handle. Alternatively, alias attributes let users have a fixed username but also sign in using a verified email or phone.

Beyond passwords, you can allow passwordless sign-in with email or SMS one-time codes, and passkeys (WebAuthn), on the plans that support these features. Federated sign-in through Google, Apple, SAML, or OIDC is a separate path.

Take quiz
What lets users sign in with a verified email while keeping a fixed username?
Alias attributes
Resource servers
Pre-sign-up trigger
Identity pool roles
Which of these is a valid passwordless method for Cognito?
SSH key upload
Kerberos ticket
Passkeys (WebAuthn)
IAM access key

12. How do you enable MFA in a Cognito user pool?

In the user pool's authentication settings, set MFA to Required or Optional (or off). Then pick the allowed second factors: authenticator app (TOTP), SMS, or email message on the plans that support it.

  • Required - every user must set up a second factor.
  • Optional - users choose to enroll, or you use adaptive authentication to trigger it based on risk.
  • SMS MFA needs SNS permissions and an SMS-capable setup, and the phone number must be verified.

TOTP is generally preferred over SMS because SMS can be intercepted or SIM-swapped, and it avoids per-message costs.

Take quiz
Which MFA factor avoids SMS delivery and SIM-swap risk?
SMS text message
Security question
TOTP authenticator app
Static backup password
Which MFA mode lets each user decide whether to enroll?
Optional
Required
Enforced by IAM
Disabled by default and unchangeable

13. What are user pool groups in Cognito?

Groups are collections of users in a user pool that you use to manage permissions together. Membership shows up in the tokens as the cognito:groups claim, so your API can make role checks.

Each group can have an IAM role attached and a precedence number. When a user belongs to several groups, the role from the group with the lowest precedence value is used by identity pools, and it appears in the cognito:preferred_role claim.

Typical uses: admins and editors for app authorization, or mapping groups to different AWS access levels.

Take quiz
Which claim lists a user's group memberships?
custom:roles
aud
token_use
cognito:groups
If a user is in two groups with roles, which role is preferred?
The group created first
The group with the lowest precedence number
The group with the longest name
Both roles are merged

14. What identity providers can you federate with in Cognito?

A user pool can federate with social providers (Google, Facebook, Login with Amazon, Sign in with Apple), SAML 2.0 enterprise providers such as Okta, Azure AD/Entra ID, or ADFS, and any OpenID Connect (OIDC) provider.

Cognito acts as a broker. The user signs in at the external provider, and Cognito creates or updates a matching user profile and issues its own user pool tokens, so your app only handles one token format.

Attribute mapping controls which claims from the provider are copied into user pool attributes.

Take quiz
With federation, whose tokens does your app receive?
Cognito user pool tokens
The provider's raw tokens only
IAM access keys
An SSH certificate
Which protocol is used for enterprise SSO in Cognito?
LDAP bind
FTP
SAML 2.0
Kerberos over UDP

15. What is guest access in Cognito identity pools?

Guest (unauthenticated) access lets someone who hasn't signed in receive temporary AWS credentials tied to a separate, more restricted IAM role. You switch it on per identity pool.

It's useful for things like letting anonymous visitors read public content from S3 or send analytics events. Cognito issues each guest a unique identity ID so the device can be recognized.

Keep the guest role minimal: read-only access to only the specific resources needed. Anyone can obtain these credentials, so treat them as public.

Take quiz
Which role do guest users assume?
The account root role
The Lambda execution role
The unauthenticated role of the identity pool
The app client role
How should the guest role be scoped?
As narrowly as possible, treated as public
Same as admins
AdministratorAccess
Only the user pool ID

16. What are the password policy settings in Cognito?

A user pool's password policy sets the minimum length (default 8, up to 99) and whether passwords must contain uppercase letters, lowercase letters, numbers, and special characters.

It also defines how long a temporary password stays valid when an admin creates a user; the default is 7 days. If you allow admin-created users, they'll be in FORCE_CHANGE_PASSWORD status until they set a permanent one.

Changes apply to new passwords only. Existing passwords aren't re-checked until users change them.

A common pattern is keeping the defaults at 8 characters with all four character classes, and relying on MFA and compromised-credential checks for extra protection rather than very long complexity rules.

Take quiz
What is the default minimum password length?
4 characters
12 characters
16 characters
8 characters
Which status does an admin-created user with a temporary password have?
ARCHIVED
FORCE_CHANGE_PASSWORD
COMPROMISED
RESET_PENDING

17. What is a Cognito domain?

A Cognito domain is the URL where your user pool serves the hosted UI and OAuth endpoints such as /oauth2/authorize, /oauth2/token, and /login.

  • Prefix domain - https://your-prefix.auth.us-east-1.amazoncognito.com. Quick to set up, prefix must be unique in the Region.
  • Custom domain - your own name like auth.example.com. Needs an ACM certificate, which must be in us-east-1, and a DNS record.

Without a domain the OAuth endpoints and hosted UI aren't available, though direct API sign-in via the SDK still works.

Take quiz
In which Region must the ACM certificate for a Cognito custom domain live?
us-east-1
eu-west-1
The same Region as the user pool always
ap-south-1
Which Cognito feature needs a domain configured?
SRP sign-in via SDK
Lambda triggers
Hosted UI and OAuth endpoints
Group creation

18. What is the pricing model of Amazon Cognito?

User pools are billed mainly by monthly active users (MAU), meaning users who did a sign-in, token refresh, or similar operation during the month. There's a free tier, and rates differ by feature plan: Lite, Essentials, and Plus.

Higher plans add features. Essentials covers modern sign-in options like passwordless and access-token customization, while Plus adds threat protection such as adaptive authentication and compromised credential checks.

Federated users through SAML or OIDC, SMS messages, and machine-to-machine token requests can carry separate charges. Check the current pricing page before estimating a budget, since rates and plans change.

Take quiz
What is the main billing unit for Cognito user pools?
Number of app clients
GB of stored profiles
Monthly active users
Lambda trigger count only
Which plan adds threat protection like adaptive authentication?
Plus
Lite
Basic
Free tier only

19. How do you integrate Cognito with a web or mobile app?

The most common route is AWS Amplify. Its Auth library wraps sign-up, sign-in, token storage, and refresh, so you configure the pool ID and app client ID and call functions like signIn.

Other options: the AWS SDK for the Cognito Identity Provider API, a standard OIDC/OAuth library pointed at your pool's discovery URL, or a redirect to the hosted UI.

import { signIn } from 'aws-amplify/auth';

const { isSignedIn, nextStep } = await signIn({
  username: 'user@example.com',
  password: 'S3cure!pass'
});

For browser apps, use authorization code flow with PKCE and a public app client.

Take quiz
Which library wraps Cognito auth for front-end apps?
AWS Glue
AWS Batch
AWS Config
AWS Amplify Auth
Which OAuth flow suits a browser SPA using the hosted UI?
Client credentials
Authorization code with PKCE
Basic auth in URL
Resource owner password over HTTP

20. What are the user statuses in a Cognito user pool?

Every user has a status showing where they are in the account lifecycle:

Status Meaning
UNCONFIRMED Signed up but not yet verified
CONFIRMED Verified and able to sign in
FORCE_CHANGE_PASSWORD Created by an admin, must set a new password
RESET_REQUIRED Must reset password before signing in
EXTERNAL_PROVIDER Signed in through a federated IdP
ARCHIVED / UNKNOWN Legacy or unusual states

Confirmation normally happens through an emailed or texted code, or automatically with a Pre sign-up trigger that auto-confirms.

You can see and change a user's status from the console, the AdminGetUser API, or by resending the confirmation code with ResendConfirmationCode.

Take quiz
A user who signed up but hasn't entered the verification code is:
UNCONFIRMED
CONFIRMED
RESET_REQUIRED
EXTERNAL_PROVIDER
Which status is typical for a user who signed in via Google?
UNCONFIRMED
FORCE_CHANGE_PASSWORD
EXTERNAL_PROVIDER
COMPROMISED

21. How does the Cognito user pool authentication flow work?

With the default SRP (Secure Remote Password) flow, the client proves it knows the password without ever sending it. The app starts with InitiateAuth, answers a series of challenges with RespondToAuthChallenge, and gets tokens at the end.

sequenceDiagram
  participant App
  participant Cognito
  App->>Cognito: InitiateAuth (USER_SRP_AUTH, SRP_A)
  Cognito-->>App: PASSWORD_VERIFIER challenge
  App->>Cognito: RespondToAuthChallenge (signature)
  Cognito-->>App: SMS_MFA / SOFTWARE_TOKEN_MFA challenge (if enabled)
  App->>Cognito: RespondToAuthChallenge (code)
  Cognito-->>App: ID, access, refresh tokens

Other flows exist: USER_PASSWORD_AUTH (sends the password, TLS-protected), CUSTOM_AUTH for Lambda-driven challenges, and ADMIN_USER_PASSWORD_AUTH for trusted backends. Each must be enabled on the app client.

The AWS SDKs and Amplify implement the SRP math for you, so you rarely code the challenge steps by hand. If a Pre authentication trigger rejects the user, the flow stops before any challenge is issued.

Take quiz
What does SRP avoid?
Using TLS
Issuing tokens
Sending the actual password to the server
Verifying the user
Which API answers an MFA challenge?
RespondToAuthChallenge
GetId
AssumeRole
CreateGroup

22. What is the difference between a Cognito ID token and an access token?

The ID token tells your app who the user is. The access token tells an API what the caller may do. Send the access token to resource servers, not the ID token.

Aspect ID token Access token
Purpose Authentication, user identity Authorization for APIs
Key claims email, name, custom attributes, aud scope, client_id, cognito:groups
token_use id access
Audience check aud = app client ID client_id = app client ID
Used with Identity pools, UI display API Gateway scopes, custom APIs, UserInfo endpoint

Access tokens also work at the /oauth2/userInfo endpoint to fetch profile claims.

A common mistake is sending the ID token to an API that expects scopes; API Gateway then rejects it because ID tokens carry no scope claim.

Take quiz
Which token should be sent to your API to authorize a request by scope?
ID token
Refresh token
SRP verifier
Access token
Which claim differs in the access token compared to the ID token for the app client check?
iss is missing
client_id instead of aud
sub is missing
exp is missing

23. What OAuth 2.0 grant types does Cognito support?

Cognito user pools support three grants through the app client configuration:

  1. Authorization code grant - the standard for web, mobile, and server apps. Returns a code that's exchanged for tokens at /oauth2/token.
  2. Implicit grant - returns tokens directly in the redirect URL. Legacy and discouraged since tokens land in browser history.
  3. Client credentials grant - machine-to-machine access with a client ID and secret and custom scopes; no user involved.

The refresh_token grant is also available at the token endpoint for renewing sessions. Prefer authorization code with PKCE for anything user-facing.

Each grant must be switched on per app client, and the client credentials grant additionally needs a client secret and at least one custom scope from a resource server.

Take quiz
Which grant involves no user and uses a client secret?
Client credentials
Implicit
Authorization code
Device flow
Which grant puts tokens straight into the redirect URL?
Authorization code
Client credentials
Implicit grant
Refresh token

24. Why should you use the authorization code grant with PKCE in Cognito?

Public clients such as SPAs and mobile apps can't keep a secret, so a stolen authorization code could be redeemed by an attacker. PKCE (Proof Key for Code Exchange) closes that gap.

  1. The app generates a random code_verifier and sends its hash as code_challenge to /oauth2/authorize.
  2. Cognito returns an authorization code to the callback URL.
  3. The app calls /oauth2/token with the code plus the original code_verifier.
  4. Cognito hashes the verifier and compares it. A stolen code alone is useless.

It also keeps tokens out of the URL, unlike the implicit grant, so it's the recommended flow for public clients.

Amplify and most OIDC libraries generate the verifier and challenge automatically, so enabling PKCE is usually just choosing the code flow in configuration.

Take quiz
What does PKCE protect against?
Expired SSL certificates
Password reuse
Interception and reuse of the authorization code
DNS spoofing of the domain
What is sent to /oauth2/token to complete PKCE?
The code_verifier
The code_challenge only
The refresh token
The IAM role ARN

25. How does Cognito integrate with API Gateway?

For REST APIs, you add a Cognito user pool authorizer. API Gateway validates the token's signature and expiry against the pool, so no Lambda is needed. Clients send the token in the Authorization header.

  • Authorizing with an ID token - no scopes configured on the method.
  • Authorizing with an access token - you can require OAuth scopes on the method.

For HTTP APIs, use a JWT authorizer configured with the pool's issuer URL and the app client ID as audience. It also supports scope checks. For fine-grained logic like tenant checks, use a Lambda authorizer instead.

Remember that the authorizer only proves the token is valid. Checking things like tenant ownership of a record still needs to happen in your Lambda or through a Lambda authorizer.

Take quiz
For an HTTP API, which authorizer type works with Cognito tokens?
IAM policy simulator
WAF web ACL
Resource policy only
JWT authorizer
Which token lets a REST API method enforce OAuth scopes?
ID token
Access token
Refresh token
SAML assertion

26. How does an Application Load Balancer authenticate users with Cognito?

An ALB HTTPS listener can use an authenticate-cognito action. The ALB runs the OIDC authorization code flow with your user pool, so unauthenticated requests are redirected to the hosted UI before they ever reach your targets.

After login, the ALB sets a session cookie (AWSELBAuthSessionCookie) and forwards the request with headers such as x-amzn-oidc-data (user claims as a JWT signed by the ALB), x-amzn-oidc-identity, and x-amzn-oidc-accesstoken.

Requirements: an HTTPS listener, an app client with a secret, and a callback URL of https://your-alb-dns/oauth2/idpresponse. Verify the ALB-signed JWT in your app if you need to trust the headers.

This suits internal tools and legacy web apps, because the application needs no login code of its own. For public APIs, token validation at API Gateway is usually a better fit.

Take quiz
Which listener type is required for authenticate-cognito?
HTTPS
HTTP only
TCP
UDP
Which callback path does the ALB use with Cognito?
/callback/aws
/login/cognito
/oauth2/idpresponse
/auth/return

27. How does an identity pool issue temporary AWS credentials?

The app first signs in with a user pool (or other IdP), then presents that token to the identity pool. Cognito verifies it, picks an IAM role, and asks STS for short-lived credentials.

sequenceDiagram
  participant App
  participant UserPool
  participant IdentityPool
  participant STS
  App->>UserPool: Sign in
  UserPool-->>App: ID token
  App->>IdentityPool: GetId (logins map with ID token)
  IdentityPool-->>App: IdentityId
  App->>IdentityPool: GetCredentialsForIdentity
  IdentityPool->>STS: AssumeRoleWithWebIdentity
  STS-->>IdentityPool: Temporary credentials
  IdentityPool-->>App: AccessKey, SecretKey, SessionToken

The credentials expire, usually after an hour, and the app repeats the exchange to renew them.

The identity pool never sees the password; it only trusts the token, provided you registered that user pool or provider as an authentication provider on the pool.

Take quiz
Which AWS service actually mints the temporary credentials?
KMS
Route 53
STS
CloudFront
Which token do you pass to the identity pool for a user pool login?
ID token
Refresh token
Client secret
SAML metadata

28. What is the difference between enhanced and basic authflow in identity pools?

Both flows return AWS credentials, but they differ in who chooses the IAM role and how many calls the client makes.

Aspect Enhanced (simplified) Basic (classic)
Calls GetId then GetCredentialsForIdentity GetId, GetOpenIdToken, then STS AssumeRoleWithWebIdentity
Role selection Cognito picks it from the pool config Client passes a role ARN
Security Client never handles role ARNs Client can request any role in the trust policy
Recommended Yes Only for special cases

Use enhanced by default. Basic makes sense when you must set role session policies or session duration yourself.

In the AWS console new identity pools use the enhanced flow, so most SDK code you write today will follow that path automatically.

Take quiz
Who selects the IAM role in the enhanced flow?
The client, via a role ARN
The user pool group name only
API Gateway
Cognito, based on identity pool configuration
Which call is unique to the basic flow?
GetCredentialsForIdentity
GetOpenIdToken
GetId
InitiateAuth

29. How do you validate a Cognito JWT on the backend?

Validate the token locally using the pool's public keys. Never trust a JWT just because it decodes.

  1. Download the JWKS from https://cognito-idp.<region>.amazonaws.com/<userPoolId>/.well-known/jwks.json and cache it.
  2. Match the token header's kid to a key and verify the RS256 signature.
  3. Check exp hasn't passed.
  4. Check iss equals your pool's issuer URL.
  5. Check token_use is what you expect (access or id).
  6. Check the app client: client_id for access tokens, aud for ID tokens.

A maintained library handles all this:

import { CognitoJwtVerifier } from "aws-jwt-verify";

const verifier = CognitoJwtVerifier.create({
  userPoolId: "us-east-1_EXAMPLE",
  tokenUse: "access",
  clientId: "1h57kf5cpq17m0eml12EXAMPLE"
});

const payload = await verifier.verify(token);

Cache the JWKS in memory and refresh it only when you see an unknown kid, so validation stays fast and doesn't add a network call to every request.

Take quiz
Where do you get the public keys to verify a Cognito JWT?
The pool's jwks.json endpoint
The app client secret
An IAM policy document
The identity pool ID
Which claim confirms an access token belongs to your app client?
aud
cognito:groups
client_id
auth_time

30. What are Lambda triggers in Cognito?

Lambda triggers let you run your own code at specific points in a user pool workflow, such as before sign-up or before tokens are issued. Cognito calls the function synchronously, and it can modify the response or reject the request by throwing an error.

Trigger When it runs / typical use
Pre sign-up Validate, auto-confirm, or link accounts
Post confirmation Create a DB record, send welcome mail
Pre authentication Block sign-in based on custom rules
Post authentication Log events, update last-login
Pre token generation Add or change token claims
Define / Create / Verify auth challenge Custom authentication flows
User migration Move users from a legacy system on first login
Custom message Customize verification and invite text
Custom email / SMS sender Send messages through your own provider

Synchronous triggers have a short time limit (about 5 seconds), so keep them fast.

Take quiz
Which trigger runs right before tokens are issued?
Post confirmation
Custom message
Pre token generation
User migration
Roughly how long can a synchronous trigger run before Cognito times out?
About 5 seconds
About 15 minutes
Exactly 1 hour
No limit

31. What is the Pre Token Generation trigger used for?

It runs just before Cognito issues tokens and lets you add, override, or suppress claims. Common examples: adding a tenant ID or roles pulled from a database, or hiding a claim you don't want exposed.

The original (V1) event customizes the ID token only. The newer V2 event, available on the Essentials and Plus feature plans, can also customize access token claims and scopes and supports complex claim types like arrays and objects.

export const handler = async (event) => {
  event.response = {
    claimsAndScopeOverrideDetails: {
      accessTokenGeneration: {
        claimsToAddOrOverride: { tenant: "acme" }
      }
    }
  };
  return event;
};

Some claims are protected (for example sub, iss, exp) and can't be changed.

Because the trigger runs on every sign-in and every token refresh, keep the logic light and cache any database lookups to avoid slowing down authentication.

Take quiz
Which version lets you customize access token claims?
Version 1 only
The Custom message trigger
The Post confirmation trigger
Trigger event version 2
Which claim can NOT be overridden by this trigger?
tenant
sub
custom:department
email

32. When would you use the Pre sign-up Lambda trigger?

Use it to validate or alter a registration before the user is created. Cognito passes in the attributes, and your function can allow, reject, or change the outcome.

  • Reject sign-ups from disallowed email domains by throwing an error.
  • Auto-confirm the user (autoConfirmUser) and auto-verify email or phone to skip the code step.
  • Link accounts when a federated user matches an existing one (PreSignUp_ExternalProvider).
export const handler = async (event) => {
  if (!event.request.userAttributes.email.endsWith("@corp.com")) {
    throw new Error("Only corp.com emails may register");
  }
  event.response.autoConfirmUser = true;
  return event;
};

Remember that the trigger also fires for admin-created users and federated sign-ups, so check triggerSource before applying rules meant for self-service sign-ups only.

Take quiz
How does the function block a registration?
By throwing an error
By returning autoConfirmUser false
By deleting the app client
By calling GlobalSignOut
Which trigger source signals a federated sign-up?
PreSignUp_SignUp
PostAuthentication_Authentication
PreSignUp_ExternalProvider
TokenGeneration_HostedAuth

33. How do custom authentication challenges work in Cognito?

Custom auth uses three Lambda triggers that run in a loop during the CUSTOM_AUTH flow:

  1. Define Auth Challenge - looks at the session so far and decides the next step: issue a challenge, fail, or issue tokens.
  2. Create Auth Challenge - builds the challenge, for example generates a one-time code, sends it, and stores the expected answer in privateChallengeParameters.
  3. Verify Auth Challenge Response - compares the user's answer with the stored one and sets answerCorrect.

The app answers each challenge through RespondToAuthChallenge. This pattern is used for OTP via email, CAPTCHA, or biometrics-style checks. Enable ALLOW_CUSTOM_AUTH on the app client first.

Since each challenge round trip is a separate call, store any state you need in the session, and keep the number of rounds small so login stays quick.

Take quiz
Where does Create Auth Challenge store the expected answer?
The ID token
The identity pool
privateChallengeParameters
A public claim
Which trigger decides whether to issue tokens or another challenge?
Define Auth Challenge
Verify Auth Challenge Response
Custom message
Post confirmation

34. How do you revoke Cognito tokens?

There are three main ways, depending on the scope:

  • RevokeToken (or /oauth2/revoke) - revokes one refresh token and the access tokens issued from it.
  • GlobalSignOut - the user signs out everywhere using their own access token.
  • AdminUserGlobalSignOut - an admin invalidates all of a user's tokens, useful when an account is compromised.

The catch: JWTs are validated locally, so a backend that only checks the signature and exp won't notice a revocation until the token expires. Keep access token lifetimes short, or call the userInfo endpoint for high-risk operations to confirm the token is still valid.

Token revocation is enabled by default on app clients, and revoking a refresh token invalidates every access token that was issued from it.

Take quiz
Why might a revoked access token still pass a local signature check?
Revoked tokens are re-signed
Cognito ignores revocation
Signatures never expire
Local checks don't consult Cognito, only signature and expiry
Which API lets an admin sign a user out of all sessions?
AdminCreateUser
AdminUserGlobalSignOut
ListUsers
SetUserMFAPreference

35. How does role-based access control work in identity pools?

Identity pools decide which IAM role a user assumes through three methods:

  1. Default role - one role for authenticated users and one for guests.
  2. Choose role from token - uses the cognito:preferred_role or cognito:roles claim, which comes from user pool group role assignments.
  3. Rules-based mapping - rules like "if claim custom:dept equals finance, use role FinanceRole", with match types Equals, Contains, StartsWith, NotEqual.

You also set what happens when no rule matches: fall back to the default authenticated role, or DENY. Denying is safer. Each role's trust policy must trust cognito-identity.amazonaws.com for that identity pool ID.

In practice, group-based roles are the simplest to reason about, while rules-based mapping works better when the deciding attribute comes from a federated provider rather than from group membership.

Take quiz
Which claim carries a group's role for token-based selection?
cognito:preferred_role
custom:iam
token_use
auth_time
What is the safer setting when no mapping rule matches?
Assume admin role
Pick a random role
Deny access
Skip STS

36. How do you use attribute-based access control with Cognito?

Identity pools can turn user attributes into principal tags. The tags are attached to the session, and IAM policies reference them with ${aws:PrincipalTag/tagName}. One policy then serves many users without creating a role per team or tenant.

Example: map the custom:tenantId claim to a tenant tag, then limit S3 access to that tenant's prefix:

{
  "Effect": "Allow",
  "Action": ["s3:GetObject", "s3:PutObject"],
  "Resource": "arn:aws:s3:::app-data/${aws:PrincipalTag/tenant}/*"
}

Configure the mapping in the identity pool's attributes for access control, either with defaults or custom mappings. The role trust policy also needs the sts:TagSession permission.

ABAC scales better than one role per tenant, because adding a new tenant only requires setting an attribute and no new IAM role or policy.

Take quiz
What IAM variable references a session tag from Cognito?
aws:UserAgent
aws:SourceIp/tag
aws:PrincipalTag/tag-name
cognito:sub/tag
Which trust policy action is needed for tag passing?
sts:TagSession
s3:GetObject
iam:PassRole
kms:Decrypt

37. How do you configure SAML federation in Cognito?

Cognito acts as the service provider (SP) and your enterprise IdP such as Okta or Entra ID acts as the identity provider.

  1. In the user pool, add a SAML identity provider and upload the IdP's metadata (URL or XML).
  2. In the IdP, register Cognito with ACS URL https://<your-domain>/saml2/idpresponse and audience urn:amazon:cognito:sp:<userPoolId>.
  3. Set attribute mapping, at minimum email, from SAML attributes to user pool attributes.
  4. Enable the provider on the app client.
  5. Send users to the hosted UI with identity_provider=<name> for direct redirect, or let them pick from the login page.

Both SP-initiated and IdP-initiated sign-in are supported. Federated users are created as EXTERNAL_PROVIDER and get normal Cognito tokens.

If users reach an error after IdP login, first compare the audience value and the signing certificate in the metadata, since either mismatch makes Cognito reject the SAML response.

Take quiz
Which URL path receives SAML assertions in Cognito?
/oauth2/token
/login/saml
/.well-known/jwks.json
/saml2/idpresponse
Which user status do SAML-federated users get?
CONFIRMED with password
EXTERNAL_PROVIDER
UNCONFIRMED
RESET_REQUIRED

Without linking, a person who signs up with a password and later uses Google with the same email ends up with two separate profiles and two different sub values. The AdminLinkProviderForUser API fixes that.

It attaches the external identity (provider name, attribute name such as Cognito_Subject, and value) to an existing native user, so both sign-in methods produce the same profile.

The usual place to call it is the Pre sign-up trigger for PreSignUp_ExternalProvider: look up a user by verified email, link the identity, and let sign-in continue. Only link when the provider's email is verified, or someone could hijack an account by claiming its email.

After linking, the person keeps a single sub, so downstream records keyed by that value stay consistent no matter which sign-in method they choose.

39. How do you migrate existing users into Cognito?

Cognito can't import password hashes, so the choice is between two approaches:

Approach How it works Trade-off
CSV import job Bulk upload of profile attributes Users land in RESET_REQUIRED and must reset their password
User migration Lambda trigger On a user's first sign-in, Lambda checks the old system and returns attributes Seamless, no reset, but the old system must stay online until everyone has logged in

With the trigger (a "lazy" migration), Cognito stores the password entered at login and creates the user. It fires for UserMigration_Authentication and for forgot-password flows. Many teams combine both: trigger for active users, then CSV import for dormant ones.

Whichever route you take, decide beforehand which attributes must be marked verified, since email and phone verification flags affect later password recovery.

Take quiz
What status do CSV-imported users have?
CONFIRMED with password
EXTERNAL_PROVIDER
RESET_REQUIRED
ARCHIVED
Which approach avoids forcing a password reset?
User migration Lambda trigger
CSV import
Custom message trigger
Hosted UI branding

40. How does adaptive authentication work in Cognito?

Adaptive authentication is part of threat protection on the Plus feature plan. Cognito scores each sign-in attempt as low, medium, or high risk using signals like device, IP address, location, and past user behavior.

You choose what happens at each risk level: allow, require MFA (or optional MFA), or block. It also checks for compromised credentials and can force a password change or block the sign-in.

  • Audit-only mode logs risk without acting, good for tuning first.
  • Full-function mode enforces the actions.
  • Users can be notified by email about risky attempts, and their feedback ("this was me") refines scoring.

Adaptive authentication needs the user's IP address to score correctly, so pass it from your backend with the UserContextData parameter when calls don't come straight from the client.

Take quiz
Which action is NOT a typical adaptive authentication response?
Require MFA
Block sign-in
Allow sign-in
Deleting the user pool
Which mode logs risk scores without enforcing actions?
Full-function
Audit-only
Passwordless
Hosted

41. How do you handle Cognito API throttling?

Cognito enforces per-Region request quotas grouped by operation type (sign-in, sign-up, token requests, and so on). When you exceed them you get a TooManyRequestsException or a throttling error, and calls fail until the rate drops.

  1. Retry with exponential backoff and jitter; the AWS SDKs do this by default.
  2. Cache tokens until they expire. A very common cause is requesting a client-credentials token per API call.
  3. Use refresh tokens instead of full sign-ins.
  4. Avoid calling Admin* APIs on every request; store what you need in your own database.
  5. Request a quota increase in Service Quotas, and watch the ThrottleCount metric.

Different operation groups have separate limits, so a burst of token requests can be throttled while sign-ups continue working normally.

Take quiz
What is a frequent cause of throttling with machine-to-machine clients?
Requesting a new token for every API call
Using TLS
Having many groups
Enabling MFA
Which retry strategy helps most?
Immediate tight loop retries
Retrying once per hour
Exponential backoff with jitter
Deleting the app client

42. How do you protect a Cognito user pool with AWS WAF?

You can associate an AWS WAF web ACL with a user pool. WAF then inspects requests to the hosted UI / managed login and to public user pool API endpoints before Cognito handles them.

  • Rate-based rules throttle credential stuffing and brute force from one IP.
  • Managed rule groups block known bad inputs and IP reputation lists.
  • Geo-match and IP set rules restrict where sign-ins can come from.

Start rules in count mode to check for false positives, then switch to block. WAF complements, not replaces, adaptive authentication and MFA.

Keep in mind that WAF sees the request only, not the user's identity, so combine it with Cognito's own lockout after repeated failed password attempts.

Take quiz
Which WAF rule type helps against credential stuffing from one IP?
Size-constraint rule on JSON
S3 bucket policy
Rate-based rule
Route table rule
Why start a WAF rule in count mode?
To find false positives before blocking
To disable logging
To bypass Cognito
To make it free

43. How do you customize Cognito emails and SMS messages?

There are several layers, from simple to advanced:

  • Message templates in the console let you edit subject and body, using placeholders like {####} for the code.
  • Custom message trigger generates content per event and per user, for example localized text.
  • Custom email/SMS sender triggers let you deliver through your own provider. Cognito encrypts the code with a KMS key and your Lambda decrypts and sends it.

For email, the built-in Cognito sender has a low daily cap (about 50 emails a day) and suits testing only. Use Amazon SES in production. For SMS, Cognito uses Amazon SNS; new accounts start in the SMS sandbox and need an origination identity and a spend limit before real sends.

Test templates in a non-production pool first, because a malformed placeholder can leave users with a verification message that doesn't contain the code.

Take quiz
Which service should send production Cognito emails?
Amazon Glacier
AWS Shield
Amazon Athena
Amazon SES
Which trigger lets you send codes through your own provider?
Pre sign-up
Custom email/SMS sender
Post confirmation
Pre token generation

44. How do you troubleshoot a redirect_mismatch error in Cognito?

redirect_mismatch means the redirect_uri in the request doesn't exactly match one of the callback URLs registered on the app client. Cognito does no fuzzy matching.

Check these in order:

  1. Compare scheme, host, port, path, and trailing slash character by character.
  2. Confirm the URL is added under the same app client whose client ID you're sending.
  3. Non-localhost callbacks must use HTTPS; wildcards aren't allowed.
  4. Verify you're hitting the right pool domain and Region.
  5. For logout, the logout_uri must be in the allowed sign-out URLs.

Frameworks often add a slash or change ports between dev and prod, which is the classic cause.

If it works locally but fails in production, look for a proxy or CDN that rewrites the host or scheme before your app builds the redirect URL.

Take quiz
How does Cognito compare redirect_uri with registered callbacks?
Exact match
Prefix match
Wildcard match
Domain-only match
Which difference commonly breaks the match?
A different browser
Token lifetime
A trailing slash
MFA setting

45. What are resource servers and custom scopes in Cognito?

A resource server represents your API inside a user pool. It has an identifier (usually a URL or short string) and a list of custom scopes describing permissions, such as read and write.

The full scope name is identifier/scope, for example orders-api/read. You allow specific scopes on each app client, and the client requests them with the scope parameter. Approved scopes appear in the access token's scope claim.

Your API, or API Gateway, then checks that claim. This is what makes fine-grained API authorization and client-credentials flows possible.

Use short, consistent names for scopes and grant each app client only the scopes it needs, since scope claims are what the API will trust for authorization.

Take quiz
What is the full name of scope read on resource server orders-api?
read@orders-api
orders-api.read.scope
orders-api/read
cognito/orders-api/read
Where do approved custom scopes appear?
The scope claim of the access token
The refresh token body
The identity pool name
The Lambda role

46. How do you implement machine-to-machine authentication with Cognito?

Use the client credentials grant. There's no user; a service authenticates as itself and receives an access token with custom scopes.

  1. Create a resource server with custom scopes.
  2. Create an app client with a secret and enable the client credentials grant.
  3. Allow only the custom scopes the service needs. Standard scopes like openid aren't available in this flow.
  4. Request a token and cache it until it expires.
curl -X POST https://auth.example.com/oauth2/token \
  -u CLIENT_ID:CLIENT_SECRET \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=client_credentials&scope=orders-api/read"

No refresh token is returned. Just request a new access token when needed, and keep the secret in Secrets Manager.

Take quiz
Which scopes can an M2M app client use?
openid and profile
aws.cognito.signin.user.admin only
Any IAM action
Custom resource server scopes
Does the client credentials flow return a refresh token?
Yes, always
No
Only with MFA
Only for admins

47. How would you design multi-tenancy with Cognito?

There are two common models, and the right one depends on isolation needs and scale.

Model Pros Cons
Pool per tenant Strong isolation, per-tenant settings, easy tenant deletion Pool quotas per account, more automation and operational overhead
Shared pool with tenant attribute or groups Simple, scales to many tenants Weaker isolation, tenant checks must be enforced in your code

A hybrid works well: one shared pool, an app client per tenant, and a per-tenant SAML or OIDC provider for enterprise customers. Store custom:tenantId and inject it into tokens with a Pre token generation trigger, then enforce it in your API and in IAM through principal tags.

Decide early, since moving tenants from a shared pool into separate pools later means recreating users, and password hashes can't be exported.

Take quiz
Which model gives the strongest tenant isolation?
A separate user pool per tenant
One shared pool with a custom attribute
One shared app client
One shared group
How can tenant ID be added to tokens?
Custom message trigger
SES template
Pre token generation trigger
CloudFront function

48. When would you choose Cognito over a third-party identity provider?

Cognito is a strong pick when your stack is already on AWS and you want tight integration with API Gateway, ALB, IAM, and Lambda at low cost per user.

Factor Cognito Third-party IdP (Auth0, Okta, etc.)
AWS integration Native (identity pools, authorizers) Works, but needs more glue
Cost at scale Usually lower per MAU Often higher, richer plans
Customization Lambda triggers, limited UI control Broader extensibility and admin UX
Feature depth Solid core, some gaps Often more out-of-the-box features

Pick a third-party provider if you need deep workflow customization, extensive prebuilt integrations, or an advanced admin experience. Also weigh lock-in, since user pools can't export password hashes.

A short proof of concept with your real login, federation, and migration requirements usually reveals gaps faster than comparing feature lists.

Take quiz
Which is a genuine Cognito advantage in an AWS-heavy stack?
It exports password hashes
It replaces VPCs
Native integration with API Gateway and IAM
It hosts your database
Which lock-in concern applies to Cognito?
Password hashes cannot be exported
Tokens are not JWTs
No MFA support
No SAML support

49. How should you store Cognito tokens in a browser app?

Any token reachable by JavaScript can be stolen by an XSS attack, so the safest place depends on your architecture.

Option Risk / benefit
localStorage / sessionStorage Convenient, readable by any script on the page (XSS exposure)
In-memory variable Safer against persistence, lost on refresh
HttpOnly, Secure, SameSite cookie set by a backend (BFF) Not readable by JavaScript; strongest common option

Best practice is a backend-for-frontend that performs the code exchange, keeps tokens server-side, and gives the browser only a session cookie. Also keep access tokens short-lived, enable refresh token rotation so a leaked refresh token is quickly useless, and add a strict Content Security Policy.

For native mobile apps, use the platform's secure storage, such as the iOS Keychain or Android Keystore, instead of plain preferences or files.

Take quiz
Which storage is not readable by page JavaScript?
localStorage
sessionStorage
A global window variable
HttpOnly cookie
What does refresh token rotation improve?
Access token size
A leaked refresh token becomes invalid after use
SES delivery speed
Hosted UI colors

50. How do you monitor and audit Cognito activity?

Use several sources, each covering a different angle:

  • CloudTrail records Cognito management and API calls, such as who created a user or changed a pool setting.
  • CloudWatch metrics in the AWS/Cognito namespace track sign-in and sign-up successes, token refreshes, federation results, and ThrottleCount. Alarm on failures and throttling.
  • User activity logs (on the Plus plan) capture authentication events and risk decisions, and can go to CloudWatch Logs, S3, or Firehose.
  • Lambda trigger logs in CloudWatch help debug custom logic.

For security reviews, combine these with WAF logs and alert on spikes in failed sign-ins or high-risk events.

Set alarms on unusual patterns rather than raw totals, for example a sudden jump in failed sign-ins against normal daily traffic.

Take quiz
Which service records who changed a user pool setting?
AWS CloudTrail
Amazon Inspector
AWS Trusted Advisor
Amazon Macie
Which CloudWatch metric helps detect rate-limit problems?
SignUpSuccesses
FederationSuccesses
ThrottleCount
TokenRefreshSuccesses
«
»

Comments & Discussions