Amazon Cognito User Pools: Sign-Up, Sign-In, JWT Tokens, MFA, Hosted UI and Lambda Triggers

AWS Developer Associate 55 min min read Updated: Nov 17, 2026 Intermediate
Amazon Cognito User Pools: Sign-Up, Sign-In, JWT Tokens, MFA, Hosted UI and Lambda Triggers
Intermediate Topic 1 of 3

Two Cognito Services

ServiceQuestion it answersResult
User poolsWho is this user? (authentication)A directory with sign-up, sign-in, MFA, and JWT tokens
Identity pools (federated identities)What AWS resources can this user access? (authorization to AWS)Temporary AWS credentials (next lesson)

A very common design: user pool signs the user in, an identity pool exchanges the token for AWS credentials (for example to upload to S3), or API Gateway checks the user pool token directly.

User Pool Features

  • Email, phone or username sign-in with password policy, email or SMS verification and account recovery
  • MFA (SMS, TOTP authenticator app, email, passkeys in newer plans) and adaptive authentication (risk-based, in advanced security)
  • Social identity providers (Google, Facebook, Apple, Amazon), OIDC and SAML enterprise providers
  • Hosted UI and managed login pages with OAuth 2.0 and OpenID Connect
  • Groups and custom attributes (custom:tenant)
  • Lambda triggers to customize flows
  • Feature plans and pricing change. Check the current pricing page

The Tokens

TokenPurposeLifetime (configurable)Send to
ID tokenWho the user is: claims like sub, email, cognito:groups, custom attributes5 minutes to 1 day (default 1 hour)Your app and API Gateway Cognito authorizer
Access tokenWhat the user may do: scopes and groups. Used with APIs and the Cognito API5 minutes to 1 day (default 1 hour)Resource servers / APIs (JWT authorizer)
Refresh tokenGet new ID and access tokens without logging in again60 minutes to 10 years (default 30 days)Only to Cognito, never to APIs
json { "sub": "a1b2c3d4-0000-4000-8000-123456789012", "cognito:groups": ["admins"], "email": "asha@example.com", "email_verified": true, "iss": "https://cognito-idp.ap-south-1.amazonaws.com/ap-south-1_AbCdEfGhI", "aud": "3n4b5urk1ft4fl3mg5e62d9ado", "token_use": "id", "exp": 1763380000 }
  • **sub is the permanent unique user id**. Use it as your database key, not the email or username
  • A JWT has header.payload.signature. The payload is only base64 encoded, not secret. Do not put secrets in it
  • To verify a token check: signature using the pool's JWKS public keys (https://cognito-idp.REGION.amazonaws.com/POOL_ID/.well-known/jwks.json), iss, aud (ID token) or client_id (access token), token_use, and exp
  • API Gateway and ALB can verify tokens for you

Sign Up and Sign In with the SDK

python import boto3, hmac, hashlib, base64 cog = boto3.client("cognito-idp", region_name="ap-south-1") CLIENT_ID = "3n4b5urk1ft4fl3mg5e62d9ado" # 1. register cog.sign_up(ClientId=CLIENT_ID, Username="asha@example.com", Password="Str0ng!Passw0rd", UserAttributes=[{"Name": "email", "Value": "asha@example.com"}]) # 2. confirm with the code from email cog.confirm_sign_up(ClientId=CLIENT_ID, Username="asha@example.com", ConfirmationCode="123456") # 3. sign in (server-side or test; browsers use SRP through Amplify/Cognito SDK) r = cog.initiate_auth(ClientId=CLIENT_ID, AuthFlow="USER_PASSWORD_AUTH", AuthParameters={"USERNAME": "asha@example.com", "PASSWORD": "Str0ng!Passw0rd"}) tokens = r["AuthenticationResult"] # IdToken, AccessToken, RefreshToken, ExpiresIn # 4. renew r2 = cog.initiate_auth(ClientId=CLIENT_ID, AuthFlow="REFRESH_TOKEN_AUTH", AuthParameters={"REFRESH_TOKEN": tokens["RefreshToken"]})
Auth flowUse
USER_SRP_AUTHRecommended for apps: password never sent, SRP proof instead. Use Amplify or a Cognito SDK
USER_PASSWORD_AUTHSends password to Cognito over TLS. Simpler, used for migration and tests
CUSTOM_AUTHCustom challenge flow with Lambda triggers (passwordless, OTP)
REFRESH_TOKEN_AUTHRenew tokens
ADMIN_USER_PASSWORD_AUTHServer-side with IAM credentials

App Clients

  • An app client is how an app talks to the pool. Public clients (browsers, mobile) must not have a client secret. Confidential server apps can have one
  • Configure allowed OAuth flows (authorization code with PKCE is recommended; implicit is discouraged), callback URLs, scopes and token lifetimes
  • Use a separate app client per application

Hosted UI and OAuth 2.0

text 1. App redirects to https://login.example.com/oauth2/authorize?response_type=code&client_id=...&redirect_uri=https://app.example.com/cb&scope=openid+email&code_challenge=... 2. User signs in (password, MFA, or Google/SAML) 3. Cognito redirects back with ?code=abc 4. App (or backend) POSTs the code + code_verifier to /oauth2/token and receives the tokens
  • Add a custom domain with an ACM certificate (the certificate must be in us-east-1)
  • Scopes such as openid, email, profile and custom scopes from a resource server (for example orders/read) protect your APIs
  • Client credentials flow supports machine-to-machine access with custom scopes

Groups and Authorization

  • Put users in groups (admins, customers). The ID and access tokens include cognito:groups
  • Check the claim in your backend or use API Gateway authorizer context: event.requestContext.authorizer.claims['cognito:groups']
  • Groups can be linked to IAM roles (identity pools) for different AWS permissions
  • For fine-grained app permissions many teams also use Amazon Verified Permissions or their own database

Lambda Triggers

TriggerWhenTypical use
Pre sign-upBefore a user is createdAuto-confirm, block certain email domains
Post confirmationAfter sign-up is confirmedCreate a profile row in DynamoDB, send a welcome email
Pre authenticationBefore sign-inDeny blocked users
Post authenticationAfter sign-inLog analytics
Pre token generationBefore tokens are issuedAdd or change claims, override groups
Custom messageBefore email or SMS is sentCustom text and templates
User migrationUser not found at sign-inMigrate users lazily from an old database
Define / create / verify auth challengeCustom auth flowPasswordless OTP
python def handler(event, context): # Post confirmation trigger: create a user profile import boto3 sub = event["request"]["userAttributes"]["sub"] email = event["request"]["userAttributes"]["email"] boto3.resource("dynamodb").Table("Users").put_item(Item={"userId": sub, "email": email}) return event # triggers must return the event
Triggers have a 5 second limit Cognito waits only about 5 seconds for a trigger. Keep them fast and avoid heavy work.

Securing Your Backend with the Token

python # Lambda behind an API Gateway Cognito/JWT authorizer def handler(event, context): claims = event["requestContext"]["authorizer"]["jwt"]["claims"] # HTTP API user_id = claims["sub"] return {"statusCode": 200, "body": f"hello {user_id}"}
  • Never trust a user id sent in the body. **Use sub from the verified token**
  • Store tokens in HTTP-only secure cookies or memory in browsers, not localStorage if you can avoid it (XSS risk)
  • Use short access token lifetimes and refresh tokens, and revoke refresh tokens on sign-out (GlobalSignOut or RevokeToken)

Practice Tasks

  1. Create a user pool and an app client without a secret
  2. Sign up, confirm and sign in with boto3 and inspect the ID token at jwt.io style decoder (do not paste real tokens into public sites)
  3. Enable the hosted UI and sign in with the authorization code flow
  4. Add a post-confirmation trigger that writes to DynamoDB
  5. Protect an HTTP API route with a JWT authorizer and call it with and without a token

Conclusion

User pools authenticate users and issue ID, access and refresh tokens (JWTs). Verify tokens using the JWKS, use sub as the user id, use the hosted UI with authorization code plus PKCE, add groups and Lambda triggers, never put secrets in public clients, and let API Gateway validate tokens.

Quick Summary: two Cognito services; features; tokens; sign-up/sign-in; app clients; hosted UI; groups; triggers; backend security.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators