Amazon Cognito User Pools: Sign-Up, Sign-In, JWT Tokens, MFA, Hosted UI and Lambda Triggers
Two Cognito Services
| Service | Question it answers | Result |
|---|---|---|
| User pools | Who 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
| Token | Purpose | Lifetime (configurable) | Send to |
|---|---|---|---|
| ID token | Who the user is: claims like sub, email, cognito:groups, custom attributes | 5 minutes to 1 day (default 1 hour) | Your app and API Gateway Cognito authorizer |
| Access token | What the user may do: scopes and groups. Used with APIs and the Cognito API | 5 minutes to 1 day (default 1 hour) | Resource servers / APIs (JWT authorizer) |
| Refresh token | Get new ID and access tokens without logging in again | 60 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
}
- **
subis 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) orclient_id(access token),token_use, andexp - 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 flow | Use |
|---|---|
USER_SRP_AUTH | Recommended for apps: password never sent, SRP proof instead. Use Amplify or a Cognito SDK |
USER_PASSWORD_AUTH | Sends password to Cognito over TLS. Simpler, used for migration and tests |
CUSTOM_AUTH | Custom challenge flow with Lambda triggers (passwordless, OTP) |
REFRESH_TOKEN_AUTH | Renew tokens |
ADMIN_USER_PASSWORD_AUTH | Server-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,profileand custom scopes from a resource server (for exampleorders/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 includecognito: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
| Trigger | When | Typical use |
|---|---|---|
| Pre sign-up | Before a user is created | Auto-confirm, block certain email domains |
| Post confirmation | After sign-up is confirmed | Create a profile row in DynamoDB, send a welcome email |
| Pre authentication | Before sign-in | Deny blocked users |
| Post authentication | After sign-in | Log analytics |
| Pre token generation | Before tokens are issued | Add or change claims, override groups |
| Custom message | Before email or SMS is sent | Custom text and templates |
| User migration | User not found at sign-in | Migrate users lazily from an old database |
| Define / create / verify auth challenge | Custom auth flow | Passwordless 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
subfrom the verified token** - Store tokens in HTTP-only secure cookies or memory in browsers, not
localStorageif you can avoid it (XSS risk) - Use short access token lifetimes and refresh tokens, and revoke refresh tokens on sign-out (
GlobalSignOutorRevokeToken)
Practice Tasks
- Create a user pool and an app client without a secret
- 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)
- Enable the hosted UI and sign in with the authorization code flow
- Add a post-confirmation trigger that writes to DynamoDB
- 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.

