Amazon Cognito identity services
Amazon Cognito provides application identity for local user pools. It manages pool and user state, checks credentials and second factors, sends verification messages, issues JWTs, supports passkeys, and provides browser-based OAuth sign-in. Its pool state connects to Lambda for custom decisions and to SES, SNS, or a KMS-backed custom sender for user messages.
System model
The Cognito service joins a user directory with app-client policy and token issuance. A user pool is the security boundary. An app client selects which sign-in, OAuth, and user-management paths a caller may use.
JSON API boundary
The Cognito JSON API maps action names to pool, user, client, MFA, recovery, managed-login branding, OAuth, passkey, and resource operations. It checks the region of pool identifiers before the operation runs. It then returns Cognito-shaped success or error responses; request routing and shared protocol behavior are described in request routing and protocols.
The boundary also preserves important request distinctions. It passes client metadata to flows that can invoke Lambda, keeps optional MFA and branding members separate from absent members, and validates values that affect authentication policy before the service changes state.
References: src/…/CognitoJsonHandler.java• L46-156 src/…/CognitoJsonHandler.java• L227-294 src/…/CognitoJsonHandler.java• L1584-1648
User pool state
A user pool holds the rules and resources that define an application identity space. It includes users, aliases, password and sign-in policy, MFA and passkey settings, recovery settings, Lambda trigger references, message settings, custom-sender KMS requirements, app clients, groups, resource servers, identity providers, domains, and managed-login branding.
When a pool has no explicit sign-in policy, it presents password as its first factor. The pool tier also limits newer choice-based sign-in features. Account recovery settings must choose either administrator-only recovery or self-service mechanisms. Contact attributes can require verification before a new value replaces the current one.
Pool IDs and ARNs include region and account scope. Requests that name a pool are checked against the request region. Deleting a pool also removes its users, clients, groups, resource servers, providers, revoked-token records, and verification codes. Deletion protection and an attached domain can block deletion.
Pool signing keys and refresh-token signing state support token checks after the pool is created. Challenge sessions, passkey ceremonies, and managed-login browser sessions are short-lived runtime state. A service restart can therefore end an unfinished sign-in even though the pool and user records remain.
References: src/…/CognitoService.java• L391-415 src/…/CognitoService.java• L689-724 src/…/CognitoService.java• L1042-1102
User identity state
A user has a canonical name, status, enabled flag, attributes, password state, group membership, and optional MFA or passkey state. Pools that use an email or phone number as a username keep an immutable canonical identifier and resolve sign-in through the current alias. Classic pools keep the supplied username.
Sign-in matching follows the pool's case rule. A case-insensitive pool treats usernames and supported sign-in attributes such as email and preferred username as equal after case normalization. This rule also applies when a challenge response names the user, so a change in case does not break an active authentication session.
User status controls whether a credential check can proceed. Confirmation, temporary-password, reset-required, disabled, external-provider, and deleted-user states affect later sign-in and token use. Contact changes can remain pending until the new email or phone number is verified. Software-token enrollment has pending setup state, while the active factor keeps its device and one-use-code state. Federated users retain the provider and subject that identify their external account.
References: src/…/CognitoUser.java• L13-47 src/…/CognitoUser.java• L61-138 src/…/CognitoService.java• L6738-6849 src/…/CognitoAuthFlowHandler.java• L433-485
App client state
An app client is the caller-facing policy for a pool. It binds authentication flows to a pool and can also define OAuth grants, callback and logout URLs, scopes, client credentials, readable attributes, and challenge-session lifetime.
The client configuration is part of the authentication contract. A flow that is not enabled by ExplicitAuthFlows is rejected before credentials are accepted. A client with no stored flow list uses Cognito's default flow set rather than enabling every flow. OAuth requests must also match the client's allowed flow, provider, scope, callback, and logout settings. Authentication challenge sessions use the client's configured validity period, which is constrained to the supported range.
References: src/…/CognitoAuthFlowHandler.java• L195-219 src/…/CognitoAuthFlowHandler.java• L225-259 src/…/CognitoAuthFlowHandler.java• L278-310 src/…/CognitoService.java• L1292-1322 src/…/CognitoService.java• L1447-1455
Authentication flows
Authentication begins with a pool user and app client, then produces tokens or a challenge. Password, SRP, choice-based, custom, passkey, and refresh flows share the same user eligibility rules and trigger checks.
Credential flows
The JSON API supports password authentication, SRP authentication, custom Lambda-driven authentication, choice-based USER_AUTH, and refresh-token authentication. Admin variants use a pool ID and can use admin password flows. Each multi-step flow returns a session that binds the next response to the pool, client, user, and expiry time.
The choice-based flow presents the factors allowed by the pool's sign-in policy and the user's state. Its supported choices include password, email OTP, SMS OTP, and WebAuthn when the user and pool are configured for them. USER_AUTH requires the Essentials tier or higher. Custom authentication requires the DefineAuthChallenge, CreateAuthChallenge, and VerifyAuthChallengeResponse triggers.
Unknown users can receive simulated choice-based challenges when the client prevents user-existence errors. These sessions never authenticate a user, which keeps the first response from revealing whether an account exists. A choice-based response must use the session issued for that challenge and the same pool and client. Challenge sessions expire using the client setting and are consumed when the answer is accepted. The first factor can end in a token result, a new-password challenge, an MFA setup challenge, or an MFA code challenge. Refresh authentication checks the pool, client, token lifetime, user, and revocation state before issuing new tokens.
Choice-based email and SMS OTP challenges use the same verification and message boundary as other Cognito codes. If delivery fails, Cognito invalidates the stored code and reports an internal delivery failure rather than leaving a retry blocked by a code the user did not receive.
References: src/…/CognitoAuthFlowHandler.java• L195-259 src/…/CognitoAuthFlowHandler.java• L1039-1081 src/…/CognitoAuthFlowHandler.java• L1141-1162 src/…/CognitoAuthFlowHandler.java• L1281-1357 src/…/CognitoService.java• L6772-6825
Sign-in event history
Sign-in event history records password-based sign-in attempts for pools with Plus advanced security in audit or enforced mode. It gives administrators a view of the sign-in result and the challenges used without making event storage part of the authentication decision.
A correct password starts an event as InProgress. The event becomes Pass only when the flow issues tokens. A failed password records Fail, while a successful MFA step adds an Mfa success challenge. The event belongs to the user's sub, so deleting and recreating a username starts a new history. Recording or completing an event can fail without blocking sign-in.
AdminListUserAuthEvents returns the user's events newest first. It supports pages of up to 60 events and uses a cursor so a new event does not shift the next page.
References: src/…/CognitoAuthFlowHandler.java• L592-609 src/…/CognitoAuthFlowHandler.java• L736-743 src/…/CognitoAuthFlowHandler.java• L2592-2604 src/…/CognitoService.java• L4014-4179 src/…/CognitoAuthEvent.java• L9-15
This diagram shows how a credential request moves through client policy, user checks, optional triggers, challenges, and token issuance.
flowchart TD
A[Authentication request] --> B[Resolve pool and app client]
B --> C{Client flow allowed?}
C -- No --> X[Reject request]
C -- Yes --> D[Resolve user and check status]
D --> E[Run pre-authentication or custom challenge]
E --> F{First factor valid?}
F -- No --> X
F -- Yes --> G{Password, setup, MFA, or passkey state?}
G -- Challenge --> H[Verify next challenge]
H --> G
G -- Tokens --> I[Run post-authentication and pre-token triggers]
I --> J[Issue signed tokens]
References: src/…/CognitoAuthFlowHandler.java• L192-219 src/…/CognitoAuthFlowHandler.java• L487-559 src/…/CognitoAuthFlowHandler.java• L1016-1057 src/…/CognitoAuthFlowHandler.java• L1245-1325
Passkey authentication
Passkey authentication uses WebAuthn credentials as a choice-based first factor. The pool must allow WEB_AUTHN, the user must register a passkey, and the browser or device must answer a short-lived challenge for the same relying party.
Registration returns browser creation options and stores a verified passkey. Sign-in checks the ceremony origin, relying-party identity, user presence, optional user verification, signature, and signature counter. A user can keep up to 20 passkeys. A user-verified passkey can also satisfy MFA when the pool allows multi-factor user verification and the user enables passkey MFA.
The access-token API supports registration, listing, and deletion. Managed login does not provide a passkey page, so passkey sign-in uses the choice-based API flow.
References: src/…/CognitoService.java• L3804-3850 src/…/CognitoService.java• L3984-4002 src/…/CognitoAuthFlowHandler.java• L1134-1185
Token lifecycle
Cognito issues RS256-signed access and ID tokens, plus refresh tokens for user sign-in. The issuer is tied to the pool. Discovery and JWKS endpoints expose the issuer and public key data that downstream OIDC clients need to validate tokens.
Access tokens identify the pool, client, user, token use, scopes, and token family. ID tokens carry user-facing identity claims subject to the client's readable-attribute rules. Group claims and pre-token trigger changes can affect the token claims, but core identity claims remain protected.
Machine-to-machine client_credentials grants issue access tokens without a user. When the pool's pre-token trigger uses Lambda version V3_0, Cognito invokes PreTokenGeneration with the TokenGeneration_ClientCredentials source. The trigger can add allowed claims and change scopes through the supported scope fields. It cannot replace protected machine-token claims or use a different client ID as aud. Lambda versions V1_0 and V2_0 do not change these tokens.
Global sign-out and token revocation record token or token-family invalidation. Later access-token, refresh-token, user-info, and API Gateway checks reject revoked tokens, expired tokens, tokens from another pool, and tokens whose user no longer exists. See IAM and authentication for the shared IAM authorization model and API Gateway for downstream Cognito authorization.
The original sign-in time is carried in the authorization code and refresh token. Tokens issued after managed login, federation, or refresh therefore keep the same auth_time instead of treating each token exchange as a new sign-in.
User-owned API operations require the aws.cognito.signin.user.admin access-token scope. Cognito bearer tokens are separate from IAM SigV4 credentials and IAM policy decisions.
The hosted /oauth2/userInfo endpoint verifies a bearer access token before it resolves the user from the token subject and pool. It returns standard OIDC profile claims and raw custom:* attributes for both GET and POST requests. On a custom domain, the token must also belong to the pool pinned to that domain.
References: src/…/CognitoService.java• L4445-4459 src/…/CognitoService.java• L4518-4563 src/…/CognitoService.java• L4647-4673 src/…/CognitoService.java• L4750-4788 src/…/CognitoAuthFlowHandler.java• L1917-1947 src/…/CognitoWellKnownController.java• L15-70
MFA and account recovery
MFA combines a pool-level mode with user-level factor registration and preference. Account recovery is a separate pool policy that decides whether a user can replace a password without administrator help.
Software-token MFA
Software-token MFA is a TOTP factor. A user first associates a secret, verifies a code, and then has an authenticator that can be enabled or preferred. A required-MFA pool asks users without an authenticator to complete setup. An optional-MFA pool asks for a code only after the user enables the factor preference.
Only one factor can be preferred at a time. Turning a preference off removes the user's sign-in requirement. The pool can require or allow software-token MFA with ON or OPTIONAL; OFF removes the pool's stored software-token configuration. Message-based MFA uses separate SMS and email settings and is delivered when the pool has the required delivery configuration and the user has a reachable contact.
A software-token challenge accepts the current TOTP time step and one adjacent step. A successful step is consumed so it cannot answer the same challenge again. Repeated failed answers exhaust the challenge's limited attempt budget.
References: src/…/CognitoService.java• L773-873 src/…/CognitoAuthFlowHandler.java• L328-403 src/…/CognitoAuthFlowHandler.java• L433-485 src/…/CognitoTotp.java• L8-35
Message-based MFA
Message-based MFA sends a one-time code to a user's phone or email after the first factor. SMS MFA needs pool SMS delivery settings and a phone number. Email MFA needs an email MFA configuration and an email address. In optional mode, the user must enable the factor; in required mode, each reachable factor offered by the pool can take part in sign-in.
The user can receive one factor directly or choose between several with SELECT_MFA_TYPE. A valid code consumes the MFA code, marks the destination attribute as verified, and issues tokens. A wrong code leaves the challenge session available for another attempt until the code limits apply. A recent code can be reused for a new challenge while the delivery rate limit is active.
References: src/…/SmsMfaSettings.java• L8-27 src/…/CognitoAuthFlowHandler.java• L2138-2308 src/…/CognitoService.java• L6381-6414
Passkey MFA
Passkey MFA lets a user-verified WebAuthn sign-in stand in for a second factor. The pool's WebAuthnConfiguration controls the relying party, user-verification preference, and whether a passkey can satisfy MFA. The user must also enable passkey MFA in the user's factor preference.
The pool accepts passkey settings alongside its MFA configuration. A missing relying-party ID can use the pool's custom or prefix domain. The ceremony must use HTTPS, or local HTTP on a localhost origin, and the passkey must answer the active challenge.
References: src/…/WebAuthnConfiguration.java• L6-23 src/…/CognitoService.java• L783-873 src/…/CognitoService.java• L3931-3977 src/…/CognitoUser.java• L131-138
Password recovery
Self-service recovery starts with ForgotPassword and ends with ConfirmForgotPassword. The first call sends a reset code to the user's configured recovery contact. The second call consumes that code and sets a permanent password.
When the pool uses admin_only recovery, self-service recovery and administrator reset are refused because the administrator must set the replacement password. An administrator reset marks the user RESET_REQUIRED and clears the current password. The local managed-login page does not provide a new-password or reset page, so users in those states must use the API or an administrator action.
References: src/…/CognitoService.java• L4030-4087 src/…/CognitoAuthFlowHandler.java• L529-568 src/…/CognitoJsonHandler.java• L1072-1095
Verification messages
Cognito uses short codes for sign-up confirmation, password recovery, contact-attribute verification, and email or SMS choice-based sign-in. The code service gives the plaintext code to the delivery path once and stores only a salted hash with expiry and attempt state.
Code verification
Each code has a pool, user, purpose, lifetime, resend limit, and failed-attempt limit. Email OTP sign-in codes use eight digits; sign-up, recovery, attribute, SMS OTP, and MFA codes use six digits. A successful code is single-use. Wrong, expired, repeated, or exhausted codes do not change user state. Reissuing too soon is rate-limited, and a new code replaces the active code for that purpose.
Contact verification has two possible state paths. With verification-before-update enabled, the new contact stays pending and the old verified value remains active until the code succeeds. Without that setting, the new value is stored at once but remains unverified until confirmation.
References: src/…/VerificationCodeService.java• L16-33 src/…/VerificationCodeService.java• L65-179 src/…/CognitoService.java• L4166-4261 src/…/CognitoUser.java• L18-20
Message delivery
When Cognito sends a message itself, the dispatcher selects a CustomMessage response first and the pool template second. The CustomMessage trigger can shape sign-up, recovery, resend, authentication, and contact-attribute verification messages. Its request carries ClientMetadata when that operation supplies it; sign-in code events omit absent metadata. A configured custom email sender takes over email delivery instead: Cognito encrypts the code under the pool's KMS key and sends it to the sender Lambda, so CustomMessage does not shape that message. The pool must name a KMS key when it uses a custom sender.
Verification, sign-in OTP, and MFA use distinct message sources: email MFA can use EmailMfaConfiguration, SMS MFA and SMS OTP use SmsAuthenticationMessage, and sign-up, recovery, and contact verification use VerificationMessageTemplate. The {####} placeholder is replaced with the code when Cognito formats the message.
Sign-up confirmation can use a link email instead of a code-only email. With CONFIRM_WITH_LINK, the {##link text##} placeholder becomes a confirmation URL in the text and HTML parts; if the template has no link placeholder, Cognito appends a safe link. The link opens the hosted /confirmUser page, which confirms the user and shows a result. A custom-domain link is pinned to that domain's pool and account, while a shared-host link resolves the client to the account that owns it.
Email uses the pool's configured SES sender only when the SES identity is verified for the pool's account and sending region and the From address is covered by that identity. Otherwise, delivery falls back to Cognito's default sender. SMS uses SNS. Local SES captures make sent email available to emulator clients.
Sign-up, password recovery, attribute verification, and email or SMS OTP use the same delivery boundary with different code purposes and templates. A delivery failure prevents the related operation from completing when the operation needs the message. For choice-based sign-in, a code issued before a delivery failure is invalidated so a failed send does not consume the resend window. A custom sender failure also invalidates its code, but an invitation user remains created because only delivery of its code failed.
Admin-created user invitations use the same boundary. Their templates can also replace {username} and the temporary password placeholder. If one requested medium succeeds, a failure on another medium does not undo the delivered invitation; the invitation fails only when no requested message is delivered.
References: src/…/CognitoMessageDispatcher.java• L26-45 src/…/CognitoMessageDispatcher.java• L87-161 src/…/CognitoMessageDispatcher.java• L419-457 src/…/CognitoService.java• L3605-3648 src/…/CognitoService.java• L4887-4897 src/…/CognitoConfirmUserController.java• L18-67 src/…/CognitoHtml.java• L3-22
Hosted and managed login
The OAuth surface provides authorization-code sign-in for pool users and federated OIDC users. It also provides client-credentials tokens for confidential app clients and OIDC discovery endpoints for clients that need standard metadata.
Managed login
Managed login is the browser path for users stored in the pool. The authorization endpoint checks the client, callback, scopes, and sign-in provider before it uses an existing session or redirects to the sign-in form. A successful sign-in creates a browser session and a one-time authorization code. The token endpoint checks the client, callback, pool, and PKCE proof before it redeems the code for tokens.
The local form supports password sign-in and, when the pool and client allow choice-based sign-in, email OTP sign-in. It uses a CSRF token and a session cookie. The browser session lasts one hour and the authorization code lasts five minutes. The session is bound to its pool and canonical user, and the code keeps the original sign-in time for the token's auth_time. The form does not serve password-change, password-reset, sign-up, MFA, or passkey pages. It treats username matching according to the pool's case-sensitivity rule. It also does not expose client secret or API flow checks that belong to direct authentication requests.
Managed-login choice-based sign-in keeps the same visible steps for every username. A user selects password or email OTP when the pool policy and client allow those factors. Unknown or ineligible users receive no message and cannot complete the hidden choice-based session, which prevents the form from exposing account existence or factor setup. A wrong or expired email code keeps the code page available; other sign-in failures return to the username step.
Custom domains expose the OAuth, managed-login, and sign-up confirmation routes at the domain root. Host-based routing pins the request to the domain's pool and account, so a client or token from another pool cannot use that domain. The served paths and methods are:
| Path | Methods |
|---|---|
/oauth2/authorize and /oauth2/idpresponse | GET, HEAD |
/oauth2/token and /oauth2/revoke | POST |
/oauth2/userInfo | GET, HEAD, POST |
/login | GET, HEAD, POST |
/logout | GET |
/confirmUser | GET, HEAD |
Unknown /oauth2/ paths return a Cognito-style 404, while unsupported methods return 405. HEAD uses the matching GET behavior without a response body. OPTIONS remains available to the shared CORS path. Requests on other hosts are not rewritten, and prefix domains are stored but are not routed by the local server.
References: src/…/CognitoCustomDomainFilter.java• L26-35 src/…/CognitoCustomDomainFilter.java• L47-65 src/…/CognitoCustomDomainFilter.java• L73-125 src/…/CognitoOAuthController.java• L83-353 src/…/CognitoConfirmUserController.java• L36-67 src/…/CognitoManagedLoginService.java• L47-124
OAuth CORS
OAuth CORS enables browser fetch calls to the token, revoke, and user-info endpoints. These routes echo the request origin and allow credentials on success and error responses. Preflight requests receive the requested method and headers with a 30-minute cache period. Authorization and logout remain navigation routes without OAuth CORS headers.
The OAuth CORS path applies after custom-domain requests resolve to Cognito and does not take ownership of requests marked as S3 virtual-host traffic. HEAD requests to custom-domain user-info use the GET CORS behavior. The filter also leaves origin variation visible to caches through Vary headers.
The JSON API has a separate browser response path. For an allowed origin admitted by the shared CORS policy, Cognito exposes its request and error headers while preserving existing exposed headers and configured extra exposed headers. It does not add these headers when the service is disabled, CORS headers are disabled, the request is not a browser-root JSON request, or the origin is not allowed.
References: src/…/CognitoOAuthCorsFilter.java• L22-35 src/…/CognitoOAuthCorsFilter.java• L37-69 src/…/CognitoOAuthCorsFilter.java• L71-97 src/…/CognitoCorsFilter.java• L22-48 src/…/CognitoCorsFilter.java• L50-82
OIDC federation
An OIDC identity provider lets a pool delegate browser sign-in to an external provider. Cognito creates a short-lived state transaction, sends the provider an authorization request, exchanges the returned code, maps claims to user attributes, and provisions or reconciles the federated user before issuing a local authorization code.
The state transaction preserves the pool, client, redirect URI, granted scopes, nonce, provider, relying-party state, and PKCE challenge. The relying app's callback and PKCE checks stay at Cognito. The current federation path supports registered OIDC providers and Google. Provider discovery can supply authorization, token, and claims endpoints; the provider response must supply an access token and subject.
Provider-requested scopes and app-granted scopes are separate. Cognito sends the provider its configured or requested provider scopes, while the local authorization code keeps only the scopes granted to the app client. This prevents the provider response from widening the relying app's token grant.
Federated profiles that Cognito creates without a local password have EXTERNAL_PROVIDER status. A linked local profile or a federated profile with a permanent password keeps its local sign-in state. This distinction controls whether later password sign-in is available without changing the external identity link.
The state transaction and authorization code are one-use, time-limited values. Provider details are retained with the transaction so the callback uses the provider configuration that started the request. External provider failures or invalid responses stop federation before a local authorization code is issued.
This diagram shows how Cognito keeps the relying application's security values while it delegates identity proof to the external provider.
sequenceDiagram
participant App as Relying app
participant Cognito
participant IdP as OIDC provider
App->>Cognito: Authorization request
Cognito->>IdP: Provider request with Cognito state
IdP-->>Cognito: Provider code
Cognito->>IdP: Exchange code and fetch claims
IdP-->>Cognito: Access token and subject claims
Cognito-->>App: Local authorization code and app state
App->>Cognito: Redeem code with PKCE verifier
References: src/…/CognitoFederationService.java• L43-186 src/…/CognitoOidcClient.java• L75-174 src/…/CognitoService.java• L3060-3135 src/…/CognitoAuthorizationTransaction.java• L7-35 src/…/CognitoAuthorizationCode.java• L6-24
Client-credentials grants
The client-credentials grant gives a confidential app client an access token for machine-to-machine calls. It has no user, ID token, or group membership, so its token claims describe the client and its granted scopes.
The request may pass aws_client_metadata as a JSON object whose values are strings. A V3_0 pre-token trigger receives this metadata and can adjust the permitted machine-token claims and scopes. Cognito protects claims that identify the client, token type, issuer, timing, and token scope from general claim replacement.
References: src/…/CognitoOAuthController.java• L513-622 src/…/CognitoService.java• L4750-4790 src/…/CognitoService.java• L5308-5369 src/…/CognitoAuthFlowHandler.java• L1917-1947 src/…/CognitoAuthFlowHandler.java• L2637-2667
OIDC metadata
The well-known endpoints provide the issuer, authorization endpoint, token endpoint, user-info endpoint, and signing keys for a pool. OIDC clients use this metadata to find the OAuth endpoints and validate RS256 JWTs without receiving the private signing key.
References: src/…/CognitoWellKnownController.java• L15-70 src/…/CognitoService.java• L4462-4487
Lambda triggers
Lambda triggers let a pool change enrollment, authentication, custom challenges, messages, migration, and token claims. Cognito builds an event with pool, user, client, trigger source, request data, and an empty response, then applies the trigger result at the owning stage. See Lambda for Lambda function behavior.
Blocking triggers
Pre-sign-up and pre-authentication triggers can reject a request before it changes user state or issues tokens. User migration can create a user when a password sign-in names a user that is not yet in the pool. Custom authentication requires trigger responses that define the next challenge, create its public and private values, and judge the answer.
Pre-token generation runs before token creation and can add or suppress allowed claims, groups, and access-token scopes. Core subject and username claims remain controlled by Cognito. For a client-credentials token, only a V3 trigger version runs. It receives a machine identity event rather than a user event, and its changes cannot replace protected machine claims. Trigger invocation errors and malformed responses fail the operation rather than producing an untrusted result.
References: src/…/CognitoAuthFlowHandler.java• L1481-1544 src/…/CognitoAuthFlowHandler.java• L1741-1814 src/…/CognitoAuthFlowHandler.java• L1837-1947 src/…/CognitoAuthFlowHandler.java• L2637-2667
Non-blocking triggers
Post-authentication runs after a successful first factor and can still make the sign-in fail if it returns an error. Post-confirmation is best-effort: its errors are logged and do not undo the confirmation. CustomMessage errors fall back to the pool's message template so a message can still be sent. The trigger receives operation-specific metadata when the caller supplies it.
Custom sender Lambda calls receive an encrypted code and run asynchronously. A sender that cannot be invoked is treated as a delivery failure by the Cognito operation, while the sender's own later result does not return to the caller.
References: src/…/CognitoAuthFlowHandler.java• L1775-1792 src/…/CognitoAuthFlowHandler.java• L1850-1881 src/…/CognitoService.java• L423-435
CloudFormation integration
CloudFormation can create and manage Cognito pools and their connected identity resources. A stack update must preserve the pool's identity and dependent relationships while it changes settings, clients, users, groups, domains, and provider links.
For stack ownership, replacement, and cleanup rules, see CloudFormation. For Lambda function behavior used by Cognito triggers, see Lambda. Specialized Cognito child pages can be linked here when a subsystem needs its own operational guide.
Resource relationships
The pool is the root of the Cognito resource graph. Clients, users, groups, resource servers, identity providers, domains, and branding refer back to it. OAuth endpoints and token validation must continue to resolve the same pool when a dependent resource changes.
References: src/…/CognitoService.java• L1042-1102 src/…/CognitoJsonHandler.java• L62-155
Change checklist
When these files or sections are changed, remember to consider these:
- If pool settings change, keep the create, update, describe, CloudFormation rollback, and token or challenge behavior aligned.
- If a user status, alias rule, case-sensitivity rule, or pending contact state changes, check password sign-in, choice-based sign-in, managed login, refresh-token checks, verification, and existing-token validation together.
- If MFA or WebAuthn configuration changes, keep pool mode, delivery settings, relying-party settings, user preference, registration, challenge selection, and reported auth factors consistent.
- If authentication session validity changes, keep client validation, all challenge stores, replay checks, and managed-login behavior aligned.
- If a verification purpose changes, keep its code length, lifetime, resend behavior, delivery template, trigger source, consume result, and user-state update aligned.
- If software-token MFA changes, keep TOTP drift acceptance, single-use steps, failed-attempt limits, setup state, and active user preference consistent.
- If custom sender behavior changes, keep the KMS key requirement, encryption context, Lambda event contract, code invalidation, and delivery error mapping aligned.
- If a Lambda trigger event or response changes, update every caller that maps its trigger source and preserve blocking versus best-effort behavior.
- If client-credentials pre-token behavior changes, keep metadata parsing, Lambda version gating, machine-event fields, protected claims, scope changes, and token validation aligned.
- If OAuth client, domain, or route rules change, keep callback validation, pool pinning, PKCE consumption, client authentication, logout redirects, browser sessions, user-info access, and token redemption aligned.
- If OAuth or JSON API browser behavior changes, keep route ownership, preflight handling, allowed origins, exposed headers, credentials,
HEADbehavior, and S3 virtual-host exclusion aligned. - If a federation transaction changes, preserve the separation between provider scopes and granted app scopes, and carry relying-party state and PKCE through the provider callback and local code redemption.
- If token claims or revocation changes, keep access-token scope checks, user-info resolution, API Gateway Cognito authorization, refresh flow, and global sign-out aligned.
- If a message trigger changes, keep its operation-specific source, metadata presence, placeholder values, sender handoff, and fallback template behavior aligned.
- If sign-up link confirmation changes, keep link generation, template rendering, HTML escaping, host routing, client-to-pool checks, and confirmation state updates aligned.
- If sign-in token timing changes, preserve the original authentication time through managed login, federation, authorization-code redemption, and refresh.
- If sign-in event recording changes, keep the Plus and advanced-security gate, user-
subownership, in-progress-to-pass transition, MFA challenge entry, and paginated admin listing aligned.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
A client starts a flow that is absent from ExplicitAuthFlows | Cognito rejects the request before authentication | Keep client flow policy and every supported auth entry point aligned |
| A challenge session expires or is used with another pool or client | The next challenge fails and no tokens are issued | Bind and check the session against its pool, client, user, and configured lifetime |
A choice-based response has no session from an earlier USER_AUTH request | The response cannot start an OTP or password challenge | Require the stored flow session before accepting the factor answer |
An unknown user receives a simulated USER_AUTH challenge | The flow must not reveal account existence or issue tokens | Keep simulated sessions separate and reject them before authentication |
| A case-insensitive pool compares a challenge username as an exact string | A valid response is rejected as belonging to another user | Resolve and compare challenge identities with the pool's sign-in key |
| A required MFA user has no verified software token | Sign-in returns MFA_SETUP instead of tokens | Complete software-token association and verification before the final setup response |
| A software-token code step was already used or too many answers were wrong | The MFA challenge fails even if the code is otherwise valid | Consume each accepted TOTP step once and enforce the attempt budget |
| A message MFA factor lacks pool delivery settings or a reachable contact | The factor is not offered or the code cannot be delivered | Configure the pool's SMS or email path and keep the user's contact available |
| A passkey ceremony uses the wrong origin, relying party, challenge, or signature counter | Registration or sign-in fails and no passkey is accepted | Keep the configured relying-party ID and browser ceremony data aligned |
Recovery is configured as admin_only | Self-service reset is refused and the user needs an administrator-set password | Use AdminSetUserPassword for the replacement password |
| A verification code is wrong, expired, reused, or exhausted | The user state stays unchanged and the operation fails | Issue a fresh code and respect purpose, expiry, and attempt limits |
| A custom sender is configured without a valid KMS key | Pool creation or update fails, or code delivery cannot proceed | Supply an existing, usable KMS key and keep its pool context valid |
| A configured SES sender is not verified for the pool's account and region | Cognito falls back to the default sender and logs a warning | Verify the SES identity and keep SourceArn and From within that identity |
| A choice-based OTP is issued but delivery fails | The challenge cannot complete and the failed code must not block an immediate retry | Invalidate the stored code when delivery raises an error |
| A sign-up link has no valid client, pool, or confirmation code | The confirmation page rejects the request and the user stays unconfirmed | Keep the link bound to the client and route it through the owning host or domain |
| A blocking Lambda trigger errors or returns malformed data | Sign-in, enrollment, custom auth, or token issuance fails | Return a valid Cognito trigger response and keep the function invokable through Lambda |
| A V3 client-credentials trigger tries to replace a protected claim or uses non-string metadata | The request is rejected or the protected token value remains unchanged | Send a JSON object of strings and change only claims and scopes allowed for machine tokens |
| A managed-login code is redeemed with the wrong client, callback, or PKCE verifier | The authorization code is rejected; a code that reaches the PKCE check cannot be reused | Preserve the original client, redirect URI, and S256 challenge through redemption |
| A custom-domain request uses an unsupported path or method | Cognito returns its authorization-server 404 or 405 instead of reaching another service route | Keep the custom-domain path and method map aligned with the OAuth, managed-login, and confirmation endpoints |
| A custom-domain request names a client or token from another pool | The request is rejected as unknown or invalid for that domain | Resolve the domain host first and enforce its pinned pool and account on every OAuth operation |
| An OAuth preflight targets a route outside Cognito's CORS map | The browser request does not receive the Cognito preflight or response CORS contract | Keep token, revoke, and user-info paths aligned with the CORS route map |
| An OAuth request is marked as an S3 virtual-host request | Cognito CORS headers can interfere with S3's own CORS behavior | Leave marked S3 traffic to the S3 CORS path |
| A JSON API browser origin is not admitted by the shared CORS policy | Cognito does not expose its request and error headers to that origin | Configure the allowed origin and keep CORS headers enabled |
| A federation state or authorization code is missing, expired, or reused | The callback cannot create a local authorization code | Consume each state value and code once and keep their lifetimes short |
| An OIDC provider response lacks a usable access token or subject | Federation stops before the local user and authorization code are created | Validate provider endpoints and required response claims |
| A user-info request has no valid bearer token or names a different pool from the custom domain | Cognito returns a bearer-token error and no profile data | Verify the token and enforce the domain's pinned pool before resolving the user |
| A pool is deleted while deletion protection or a domain is active | Pool deletion fails and dependent state remains | Disable deletion protection and remove the domain before deleting the pool |
| Advanced security is not enabled for a pool that lists auth events | AdminListUserAuthEvents is refused even if the user has sign-ins | Use a Plus pool with AdvancedSecurityMode set to AUDIT or ENFORCED |
| An auth event is completed after the user is deleted and recreated | The old user history must not be written to the new user | Bind events to the user's sub and verify current ownership before updates |
Key files
| File | Why to read it |
|---|---|
| src/…/CognitoService.java | Pool, user, client, token, recovery, verification, passkey, revocation, sign-in event, message delivery, client-credentials, confirmation-link, and resource-lifecycle ownership |
| src/…/CognitoAuthFlowHandler.java | Credential flows, choice-based sign-in, challenge state, message and software-token MFA, passkey challenges, Lambda trigger contracts, managed-login factor checks, and sign-in event completion |
| src/…/CognitoJsonHandler.java | Cognito JSON API operation boundary and action-to-domain routing |
| src/…/CognitoUser.java | Persistent user status, pending contact state, MFA enrollment, passkey state, and federated identity state |
| src/…/CognitoAuthEvent.java | Sign-in event shape, challenge results, event status, and user-sub ownership |
| src/…/CognitoTotp.java | Software-token MFA acceptance window and one-use challenge rules |
| src/…/CognitoOAuthController.java | Authorization, managed login, logout, PKCE, client-credentials metadata, federation callbacks, and OAuth token redemption paths |
| src/…/CognitoCustomDomainFilter.java | Host-based custom-domain routing, pool and account pinning, confirmation links, and Cognito route method behavior |
| src/…/CognitoConfirmUserController.java | Hosted sign-up confirmation-link page and shared-host versus custom-domain confirmation scope |
| src/…/CognitoHtml.java | Shared escaping rules for managed-login and confirmation HTML |
| src/…/CognitoOAuthCorsFilter.java | Browser CORS behavior for OAuth token, revoke, and user-info routes |
| src/…/CognitoCorsFilter.java | Exposed headers for allowed browser origins on the Cognito JSON API |
| src/…/CognitoManagedLoginService.java | Managed-login browser session, password and email-OTP sign-in, and authorization-code handoff |
| src/…/CognitoFederationService.java | OIDC federation transaction, provider claim mapping, scope separation, and local authorization-code creation |
| src/…/CognitoWebAuthn.java | Passkey registration and assertion checks |
| src/…/VerificationCodeService.java | Code length, lifetime, hashing, rate limits, failed attempts, and single-use behavior |
| src/…/CognitoMessageDispatcher.java | Template selection, confirmation-link rendering, Lambda message overrides, and SES or SNS delivery selection |
| src/…/CustomSenderCodeEncryptor.java | KMS-backed encryption of verification codes for custom sender Lambda events |
| src/…/CognitoWellKnownController.java | OIDC discovery and JWKS endpoints used by token consumers |