Cognito Flows, Federation and Application Security
Overview
Earlier you met Cognito user pools and identity pools. In this lesson we put them to work: choosing an OAuth flow, validating tokens in your backend, federating with enterprise or social identity providers, mapping users to IAM roles and securing the API with layers such as WAF, throttling and input validation.
Picture an airport. Passport control (the user pool) checks who you are and stamps your boarding pass (JWT). The gate agent (your API) must still read the pass carefully: is it genuine, for this flight, not expired? Airport shops (identity pool roles) only accept you for the items on your tier.
Authentication proves who you are; authorisation limits what you can do. Both are tested with scenario questions about the right Cognito component, the right grant type, and where to enforce checks.
Key Concepts
- Authorization code grant + PKCE is the recommended flow for web and mobile apps; client credentials is for machine-to-machine with resource server scopes; the implicit flow is discouraged.
- The hosted UI / managed login provides sign-in pages, social and enterprise federation and returns authorisation codes to a callback URL.
- User pools federate with Google, Facebook, Apple, Amazon, SAML 2.0 and OIDC providers and map external attributes to pool attributes.
- Groups in a user pool appear in the
cognito:groupsclaim and can map to IAM roles in an identity pool (role resolution rules). - Identity pools support authenticated and unauthenticated roles, role-based and rule-based mapping, and policy variables like
${cognito-identity.amazonaws.com:sub}. - Validate JWTs in the backend: signature (JWKS),
iss,token_use,aud/client_id,exp; or let API Gateway or ALB (OIDC authenticate action) do it. - MFA (TOTP, SMS, email), adaptive authentication and compromised credential checks are available with advanced security features.
- Layer defences: AWS WAF, API Gateway throttling, input validation, TLS everywhere, CORS, least-privilege roles and audit logging.
Detailed Notes
Choosing a flow
| Scenario | Flow |
|---|---|
| SPA or mobile app | Authorization code + PKCE |
| Server-side web app | Authorization code (with client secret) |
| Service to service | Client credentials (resource server + custom scopes) |
| Trusted first-party app, no redirect | USER_PASSWORD_AUTH / SRP (SDK based) |
PKCE: the client creates a random code_verifier, sends its hash (code_challenge) with the authorise request, and proves possession with the verifier when exchanging the code, protecting against authorisation code interception.
# Hosted UI authorize request
https://auth.example.com/oauth2/authorize?response_type=code&client_id=abc123\
&redirect_uri=https://app.example.com/callback&scope=openid+email+orders/read\
&code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM&code_challenge_method=S256
# Token endpoint
curl -X POST https://auth.example.com/oauth2/token \
-d grant_type=authorization_code -d client_id=abc123 \
-d code=$CODE -d redirect_uri=https://app.example.com/callback \
-d code_verifier=$VERIFIER
Verifying a token in a Lambda authorizer
import json, urllib.request
import jwt # PyJWT with cryptography
from jwt import PyJWKClient
REGION, POOL, CLIENT = "eu-west-1", "eu-west-1_AbC123", "abc123"
ISS = f"https://cognito-idp.{REGION}.amazonaws.com/{POOL}"
jwks = PyJWKClient(f"{ISS}/.well-known/jwks.json") # cached across invocations
def handler(event, context):
token = event["authorizationToken"].removeprefix("Bearer ")
try:
key = jwks.get_signing_key_from_jwt(token).key
claims = jwt.decode(token, key, algorithms=["RS256"], issuer=ISS,
options={"verify_aud": False})
if claims["token_use"] != "access" or claims["client_id"] != CLIENT:
raise ValueError("wrong token")
effect = "Allow"
except Exception:
effect = "Deny"
return {
"principalId": claims.get("sub", "anonymous") if effect == "Allow" else "anonymous",
"policyDocument": {"Version": "2012-10-17", "Statement": [{
"Action": "execute-api:Invoke", "Effect": effect, "Resource": event["methodArn"]}]},
}
Prefer the built-in Cognito authorizer (REST) or JWT authorizer (HTTP API) when no custom logic is needed.
Identity pool role mapping
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:PutObject"],
"Resource": "arn:aws:s3:::user-files/${cognito-identity.amazonaws.com:sub}/*"
}]
}
Role selection can use the token's cognito:preferred_role, groups with precedence, or rules on claims (for example custom:department = finance).
Federation patterns
| Pattern | Components |
|---|---|
| Social login for consumers | User pool + Google/Apple IdP |
| Enterprise SSO | User pool + SAML/OIDC IdP (Okta, Entra ID) |
| Workforce access to AWS console/CLI | IAM Identity Center |
| Direct AWS credentials for app users | Identity pool |
Customising tokens
A pre token generation Lambda can add or suppress claims, or override group membership; use it to inject tenant IDs.
Defence in depth for APIs
- TLS only; HSTS and secure cookies.
- WAF with managed rule sets (SQLi, XSS, rate-based rules) in front of API Gateway/ALB/CloudFront.
- Request validation in API Gateway models and in code; never trust client input.
- Throttling and usage plans.
- Least privilege execution roles and per-tenant authorisation checks (do not rely on hidden URLs).
- Logging: access logs, CloudTrail, and alarms on auth failures.
Common mistakes
- Using the ID token to call APIs expecting an access token.
- Skipping audience/client checks, allowing tokens from other app clients.
- Storing tokens in
localStoragefor sensitive apps; prefer secure, HTTP-only cookies via a backend-for-frontend.
Tokens and flows
| Token | Purpose | Validate |
|---|---|---|
| ID token | Who the user is (claims, groups) | Signature via the pool JWKS, iss, aud, exp |
| Access token | Authorise API calls and scopes | Signature, client_id, scope |
| Refresh token | Get new tokens (default 30 days) | Exchanged at the token endpoint |
Use the authorization code flow with PKCE for web and mobile apps; the implicit flow is discouraged. Hosted UI, social and SAML/OIDC identity providers, MFA and Lambda triggers (pre sign-up, pre token generation, post confirmation) customise the experience.
import boto3
idp = boto3.client("cognito-idp")
r = idp.initiate_auth(ClientId=CLIENT_ID, AuthFlow="USER_PASSWORD_AUTH",
AuthParameters={"USERNAME": u, "PASSWORD": p})["AuthenticationResult"]
# r["IdToken"], r["AccessToken"], r["RefreshToken"]
Auth:
Type: AWS::ApiGateway::Authorizer
Properties:
Type: COGNITO_USER_POOLS
IdentitySource: method.request.header.Authorization
ProviderARNs: [!GetAtt UserPool.Arn]
RestApiId: !Ref Api
Name: cognito
An identity pool exchanges a user pool token (or a social, SAML or guest identity) for temporary AWS credentials with an authenticated or unauthenticated role; role mapping by group or claim gives per-user permissions, and ${cognito-identity.amazonaws.com:sub} in IAM policies scopes S3 or DynamoDB access per user. Group claims (cognito:groups) drive authorisation in API Gateway and AppSync.
Real World Example
A B2B portal lets employees of customer companies sign in with their own corporate SAML providers through a Cognito user pool, and lets individual users sign in with Google. A pre token generation Lambda adds a custom:tenantId claim; the API (HTTP API with a JWT authorizer) checks scopes and the Lambda enforces that the tenant claim matches the data it reads. Files are uploaded directly to S3 using an identity pool role with a per-user prefix, and WAF rate-based rules blunt credential-stuffing attempts.
Architecture Diagram
External IdPs authenticate users; Cognito issues tokens; the API validates them and enforces scope.
- 1The user authenticates with a social or corporate identity provider.
- 2The user pool returns an authorisation code that the app exchanges (with PKCE) for tokens.
- 3The app calls the API with the access token; WAF filters malicious traffic.
- 4The authorizer validates the token and the backend enforces tenant-level authorisation.
Best Practices
- ✓Use authorization code with PKCE for public clients and no embedded secrets.
- ✓Validate signature, issuer, token_use, client and expiry on every request.
- ✓Use groups, custom claims and identity pool roles for fine-grained authorisation.
- ✓Put WAF and throttling in front of public APIs.
- ✓Enable MFA and monitor sign-in anomalies.
Common Interview Questions
Exam Tips
DVA-C02 focus
- Mobile/SPA -> authorization code with PKCE; machine-to-machine -> client credentials.
- Enterprise federation to a user pool -> SAML/OIDC IdP.
- Per-user AWS resource access -> identity pool + policy variable.
- Block SQL injection and rate-limit bad actors -> AWS WAF.
Chapter quiz
Security for Developers · 10 questions
1.A Lambda function in account A must read an S3 bucket in account B. Which approach follows best practice?
2.An application must encrypt 200 MB files using a KMS key. What is the correct approach?
3.A team needs database credentials that rotate automatically every 30 days with no application downtime. Which service should store them?
4.A policy attached to a user allows s3:DeleteObject on a bucket, but the bucket policy contains an explicit Deny for s3:DeleteObject for that user. What is the result?
5.A single-page application must authenticate users against a Cognito user pool without embedding a client secret. Which OAuth flow should it use?
6.An S3 bucket encrypted with a customer managed KMS key in account A must be read by a role in account B. What is required?
7.A Lambda function needs a database password that rotates every 30 days automatically. Which service suits best?
8.Large files must be encrypted client-side before upload so AWS never sees plaintext. What is the standard technique?
9.A public HTTPS endpoint behind CloudFront and ALB needs managed certificates that renew automatically. Which service?
10.A multi-tenant SaaS on DynamoDB must ensure tenant A can never read tenant B items. What is a strong approach?
0 of 10 answered
Finished this lesson?
0 of 46 lessons done · 0% of the course

