Authentication Basics: Cognito and Tokens
Overview
Most applications need to answer two questions: who is this user (authentication) and what may they do (authorisation). Amazon Cognito handles user sign-up, sign-in and token issuing so you do not have to build and secure a password database yourself.
Cognito has two main parts. A user pool is a user directory that signs people in and hands back JSON Web Tokens (JWTs), like a club that checks your ID and issues a membership card. An identity pool (federated identities) swaps a trusted token for temporary AWS credentials, like exchanging that card for a locker key to actual AWS resources.
This lesson gives the basics; the Security chapter goes deeper into the flows and authorisation.
Key Concepts
- A user pool provides sign-up/sign-in, MFA, password policies, social and SAML/OIDC federation, a hosted UI and JWT tokens.
- Tokens: ID token (identity claims), access token (authorisation, scopes) and refresh token (get new tokens).
- An identity pool exchanges tokens from user pools, social or SAML providers for temporary AWS credentials via STS, including guest access.
- API Gateway can use a Cognito authorizer to validate user pool tokens without custom code.
- OAuth 2.0 / OIDC flows supported: authorization code (with PKCE), implicit and client credentials.
- Lambda triggers customise flows: pre sign-up, post confirmation, pre token generation and custom auth.
- JWTs are signed; verify the signature with the pool's JWKS public keys, plus
iss,aud/client_idandexp. - App clients have an ID and optional secret; browser and mobile clients should have no secret and use PKCE.
Detailed Notes
User pools vs identity pools
| Aspect | User pool | Identity pool |
|---|---|---|
| Purpose | Authenticate users, issue JWTs | Authorise access to AWS services |
| Output | ID, access, refresh tokens | Temporary AWS credentials |
| Typical consumer | API Gateway, your backend | Mobile/web app calling S3, DynamoDB |
| Supports guests | No | Yes (unauthenticated role) |
Often both are used: sign in to the user pool, then pass the ID token to the identity pool to receive AWS credentials mapped to an authenticated IAM role.
Token contents
A JWT has three base64url parts: header, payload (claims) and signature.
{
"sub": "a1b2c3d4-...",
"iss": "https://cognito-idp.eu-west-1.amazonaws.com/eu-west-1_AbC123",
"cognito:groups": ["admins"],
"email": "ana@example.com",
"token_use": "id",
"exp": 1767225600
}
The access token has token_use: "access", scope and client_id. Use the access token to authorise API calls and the ID token to display user info.
Signing a user up and in (Python)
import boto3
idp = boto3.client("cognito-idp")
idp.sign_up(ClientId=CLIENT_ID, Username="ana@example.com",
Password="S3cure!Passw0rd", UserAttributes=[{"Name": "email", "Value": "ana@example.com"}])
resp = idp.initiate_auth(
ClientId=CLIENT_ID,
AuthFlow="USER_PASSWORD_AUTH",
AuthParameters={"USERNAME": "ana@example.com", "PASSWORD": "S3cure!Passw0rd"},
)
tokens = resp["AuthenticationResult"] # IdToken, AccessToken, RefreshToken, ExpiresIn
For web apps prefer the hosted UI with the authorization code grant + PKCE so your code never sees the password.
Protecting an API
In a SAM template a Cognito authorizer on an HTTP/REST API looks like this:
Resources:
Api:
Type: AWS::Serverless::Api
Properties:
StageName: prod
Auth:
DefaultAuthorizer: CognitoAuth
Authorizers:
CognitoAuth:
UserPoolArn: !GetAtt UserPool.Arn
The client sends Authorization: <token> (REST API Cognito authorizer accepts ID or access token with scopes configured) and API Gateway validates it.
Token lifetimes
| Token | Default | Configurable |
|---|---|---|
| ID / access | 1 hour | 5 minutes to 1 day |
| Refresh | 30 days | 60 minutes to 10 years |
Revoking a refresh token (RevokeToken) or global sign-out invalidates future refreshes, while already issued access tokens stay valid until they expire.
Lambda triggers
Triggers let you add logic: restrict sign-ups to a corporate domain (pre sign-up), add custom claims (pre token generation), send a welcome message (post confirmation), or run a passwordless custom challenge.
Common mistakes
- Trusting a JWT without verifying its signature and issuer.
- Using the ID token as an API credential when the API expects scopes.
- Embedding an app client secret in a mobile or browser app.
Bearer tokens and application-level authorisation
A JWT is a bearer token: whoever holds it can use it, so it must travel only over TLS and be short-lived. Send it in the Authorization: Bearer <token> header, never in a URL. IAM controls access to AWS APIs, but fine-grained rules inside your app (can this user edit this order?) belong in your code, using claims as input.
def authorise(claims, order):
groups = claims.get("cognito:groups", [])
scopes = claims.get("scope", "").split()
if "orders/write" not in scopes:
raise PermissionError("missing scope")
if "admins" in groups:
return True
return order["ownerId"] == claims["sub"] # users may edit only their own orders
| Mechanism | Granularity |
|---|---|
| IAM policy | AWS API actions and resources |
| Cognito groups and scopes | Coarse roles for your API |
| Custom claims (tenant, role) | Inputs to your authorisation code |
| Verified Permissions (Cedar policies) | Externalised, fine-grained application policies |
Refreshing tokens
When the access token expires, exchange the refresh token with InitiateAuth using the REFRESH_TOKEN_AUTH flow instead of asking the user to sign in again. Store refresh tokens securely and treat a refresh failure as a sign-out.
Real World Example
A fitness app needed login with email, Google and Apple, and let users upload workout photos straight to S3. The team created a user pool with social identity providers and MFA, and an identity pool that maps authenticated users to an IAM role allowing s3:PutObject on workout-photos/${cognito-identity.amazonaws.com:sub}/*. Each user can only write to their own folder, and the backend API validates access tokens using a Cognito authorizer.
Architecture Diagram
Users authenticate for tokens, then optionally exchange them for temporary AWS credentials.
- 1The user signs in to the user pool with password, MFA or a social provider.
- 2The user pool returns ID, access and refresh tokens.
- 3The app passes the ID token to the identity pool.
- 4The identity pool returns temporary credentials for the mapped IAM role.
Best Practices
- ✓Use the authorization code flow with PKCE for browser and mobile apps.
- ✓Verify token signature, issuer, audience and expiry on your backend.
- ✓Enable MFA and advanced security features for sensitive apps.
- ✓Keep access tokens short-lived and use refresh tokens securely.
- ✓Scope identity pool roles to per-user resource paths using policy variables.
Common Interview Questions
Exam Tips
DVA-C02 focus
- Sign-in and JWTs = user pool. Temporary AWS credentials = identity pool.
- Mobile app needing direct S3 access per user = Cognito identity pool.
- API Gateway with no custom code for users = Cognito authorizer.
- Cognito Lambda triggers customise sign-up and token content.
Chapter quiz
Developing on AWS · 10 questions
1.A Python script that lists objects in a bucket returns only 1,000 keys even though the bucket has many more. What should the developer do?
2.An application on EC2 receives AccessDenied even though its instance profile role has the right permissions. The server has AWS_ACCESS_KEY_ID set in the environment from an old deployment. What is the cause?
3.Many clients receive ThrottlingException and retry immediately, which keeps the service overloaded. Which change helps MOST?
4.A mobile app lets signed-in users upload photos directly to their own S3 prefix. Which combination provides this with temporary credentials?
5.A container running on ECS needs to read from DynamoDB. Which role should hold the DynamoDB permissions?
6.A batch job calls DynamoDB BatchWriteItem and occasionally loses records although no exception is raised. What is the most likely cause?
7.A GitHub Actions pipeline must deploy to AWS without storing long-lived access keys. What should you configure?
8.A developer's laptop uses the default profile but CLI calls act as the wrong account. aws configure list shows the source is 'env'. What explains this?
9.A single-page app needs per-user authorisation rules such as 'a user may edit only their own orders'. Where should this logic live?
10.An application receives ThrottlingException from several AWS APIs under load. Which combination is the best response?
0 of 10 answered
Finished this lesson?
0 of 46 lessons done · 0% of the course

