Security: Auth, Encryption & Least Privilege
System Design · Production in the Cloud · Advanced · 24 min
Explain who can call your API and what they may touch: Cognito logins, JWTs checked by API Gateway, IAM roles, KMS encryption and WAF, and validate a token's claims yourself.
A concert: the box office checks your ID once and hands you a wristband with a hologram. Every door inside just glances at the wristband: is the hologram real, is it today's colour, does it say VIP for the VIP door? Nobody looks at your ID again.
The idea in everyday words
Authentication is the box office proving who you are. Authorization is each door deciding what you may do. The wristband is a JWT: cheap to check at every door, but anyone can read what is printed on it, and it stops working at midnight. Staff (your services) do not wear wristbands, they carry a staff badge that only opens the rooms their job needs: that is an IAM role with least privilege.
AuthN vs AuthZ, and the token idea
Two different questions, often mixed up:
| Question | Name | Example |
|---|---|---|
| Who are you? | Authentication (authN) | Ana logs in with password + MFA |
| What may you do? | Authorization (authZ) | Ana may read her orders, not Bo's |
The key idea: log in once, then carry a signed token. Checking a password on every request would be slow and would spread passwords everywhere. Instead, an identity provider checks the password once and hands back a token: a small piece of text that says "this is Ana, valid until 10:15", signed so nobody can change it.
- OAuth 2.0 is the standard for getting an access token to call an API (authZ). The usual flow for web and mobile apps is authorization code + PKCE (PKCE = a one-time secret that stops a stolen code from being used).
- OpenID Connect (OIDC) sits on top of OAuth 2.0 and adds an ID token that says who logged in (authN).
- Apps get three tokens: an ID token (who you are, for the app), an access token (sent to APIs), and a refresh token (long lived, used only to get new short-lived tokens).
- In Cognito, the ID and access tokens are JWTs you can decode and verify. The refresh token is different: it is opaque and encrypted, so only Cognito can read it. Your app just stores it safely and sends it back to Cognito.
On AWS, Amazon Cognito user pools are the identity provider: sign-up, sign-in, MFA, social and SAML/OIDC federation, a hosted login page, and they issue these tokens. (Cognito identity pools are a different feature: they swap a login for temporary AWS credentials.)
JWTs: what is inside, and what NOT to put in them
A JWT (JSON Web Token) is three base64url parts joined by dots: header.payload.signature.
- header: which algorithm and which key signed it (
alg,kid). - payload: the claims. Standard ones:
iss(issuer, who made it),sub(subject, the user id),aud(audience, which app it is for),exp(expires at, in seconds since 1970),nbf(not valid before),iat(issued at), plusscopeor groups. - signature: Cognito signs its ID and access tokens with its private key (RS256). Anyone can verify with the public keys it publishes at a JWKS URL (JSON Web Key Set).
Signed is not encrypted. Base64 is just an encoding, anyone holding the token can read the payload. Try it:
import base64, json
def b64url(obj):
raw = json.dumps(obj, separators=(",", ":")).encode()
return base64.urlsafe_b64encode(raw).decode().rstrip("=")
payload = {"sub": "u-42", "email": "ana@example.com", "exp": 1700000900}
token = b64url({"alg": "RS256", "kid": "k1"}) + "." + b64url(payload) + ".fake-signature"
print(token[:40] + "...")
middle = token.split(".")[1]
middle += "=" * (-len(middle) % 4) # put back the padding
print(json.loads(base64.urlsafe_b64decode(middle))) # no key needed to READ it
So never put secrets in a JWT: no passwords, API keys, card numbers or health data. Keep it to ids, roles and expiry. Keep access tokens short lived (minutes to an hour) because a JWT cannot easily be revoked before exp: every server trusts it until then. Revocation is what the refresh token step is for.
Validating a JWT means all of these, every time:
- Signature verifies with the key whose
kidis in the issuer's JWKS (andalgis the one you expect: never acceptnone). issis your user pool.aud(ID token) orclient_id(Cognito access token) is your app.expis in the future andnbfis in the past, allowing a small leeway for clock skew.token_use/scopefits this API.
Encryption: KMS at rest, TLS in transit, Secrets Manager
At rest (stored data). AWS KMS holds keys inside hardware security modules; the key material of a KMS key never leaves KMS unencrypted. Most services just need a checkbox or a key ARN: S3 encrypts new objects by default, DynamoDB encrypts every table, and EBS and RDS can use a customer managed key you control (key policy, rotation, audit in CloudTrail).
Envelope encryption: why KMS does not encrypt your 5 GB file directly. KMS Encrypt only takes small payloads, and calling KMS for every byte would be slow. So:
- Ask KMS
GenerateDataKey: you get a data key twice, once in plaintext and once encrypted under your KMS key. - Encrypt the big file locally with the plaintext data key (AES-256-GCM), then throw the plaintext key away.
- Store the encrypted data key next to the file.
- To read: send the encrypted data key to KMS
Decrypt(IAM checks you are allowed), get the plaintext key back, decrypt the file.
The letter (data) is locked with a cheap key; that key is locked inside an envelope only KMS can open. Revoke access to the KMS key and every file becomes unreadable at once.
In transit (moving data). Use TLS (HTTPS) everywhere: AWS Certificate Manager (ACM) issues and renews certificates for CloudFront, ALB and API Gateway. Inside the VPC, use TLS to databases too.
Secrets. Database passwords and third-party API keys go in AWS Secrets Manager (or SSM Parameter Store SecureString), encrypted with KMS, fetched at runtime by a role that is allowed to read that one secret, and rotated automatically. Never in code, env files in git, or container images.
Edge protection. AWS WAF filters HTTP requests on CloudFront, ALB, API Gateway REST APIs (not HTTP APIs), AppSync and Cognito: managed rule groups (SQL injection, bad bots), IP sets and rate-based rules. AWS Shield Standard protects every AWS customer from common network DDoS attacks automatically; Shield Advanced is a paid tier with extra protection and a response team.
Equivalents: GCP Cloud KMS, Secret Manager and Cloud Armor; Azure Key Vault and Front Door WAF; open source HashiCorp Vault and ModSecurity.
How to talk about security in an interview
Walk through layers from the outside in, and give one concrete control per layer:
| Layer | Threat | Control on AWS |
|---|---|---|
| Edge | floods, bots, SQL injection | CloudFront + WAF rate rules, Shield |
| Identity | stolen passwords | Cognito with MFA, short-lived tokens |
| API | forged or expired tokens | API Gateway JWT / Cognito authorizer |
| App | user reads another user's data | ownership check on every object |
| Service | compromised function | IAM role with only the actions it needs |
| Data | stolen disk or backup | KMS encryption, key policy, CloudTrail |
| Secrets | leaked DB password | Secrets Manager with rotation |
Defence in depth: assume any one layer can fail. A leaked token should still expire soon; a hacked Lambda should still only reach one table.
Go deeper (senior / staff)
Failure modes you should name.
- Key rotation and JWKS caching. Validators cache the pool's public keys. When a token arrives with an unknown
kid, refetch the JWKS once (rate limited) instead of failing or refetching on every request. - Clock skew across fleets is why leeway exists. Keep it small (seconds), or a stolen token lives longer than you think.
- Revocation lag. Offline JWT checks never call Cognito, so a revoked session keeps working until
exp. The trade-off is latency and availability (no call per request) against how fast you can cut someone off. Shorter access-token lifetimes shrink the window; a deny-list in a Lambda authorizer closes it for emergencies.
Multi-region. A Cognito user pool is a regional resource, so treat it as a regional dependency in your DR plan. Check the Cognito docs for the current multi-Region options; common patterns are a federated external IdP, or a standby pool plus a plan for moving users. KMS multi-Region keys let the same key id decrypt in a second region, and Secrets Manager can replicate secrets, so a failover region can read data without re-encrypting it.
Cost and scale reasoning.
- A Lambda authorizer runs per request unless you cache by token; a cache TTL is a direct trade between cost and revocation speed.
- KMS request volume adds up with SSE-KMS on busy buckets. S3 Bucket Keys cut the number of KMS calls a lot.
- WAF bills per rule and per request, so put it where it filters most junk (CloudFront), not on every inner hop.
At organisation scale: SCPs as guardrails, IAM Identity Center for humans (no IAM users with long-lived keys), GuardDuty and Security Hub for detection, and CloudTrail organisation trails into a locked log-archive account.
Step by step
- Log in:
Ana signs in through the Cognito hosted page with password + MFA. The app uses the authorization code flow with PKCE.
- Get tokens:
Cognito returns an ID token, an access token with exp = now + 3600 s, and a refresh token. The ID and access tokens are JWTs signed with the user pool's private key. The refresh token is an opaque, encrypted token that only Cognito can read.
- Call the API:
The app sends GET /orders with header Authorization: Bearer . It goes through CloudFront, where AWS WAF lets it through (normal rate, no attack pattern). WAF sits on CloudFront because it cannot attach to an HTTP API directly.
- Authorizer checks:
API Gateway fetches the pool's JWKS (cached), verifies the signature with key kid=k1, checks iss = our pool, client_id = our app, exp > now. All pass.
- Least-privilege call:
Lambda runs with an execution role that may only call GetItem and Query on the Orders table. It queries pk = u-42 (taken from the token's sub, not from the URL).
- Expired path:
An hour later the same token arrives with exp < now. The authorizer returns 401 before Lambda runs. The app trades its refresh token at Cognito for a new access token and retries: 200.
- Tampered path:
An attacker edits the payload to add "admin". The signature no longer matches the content, so the authorizer returns 401. A refresh cannot fix a forged token.
Code example
import base64, json
def b64url(obj):
raw = json.dumps(obj, separators=(",", ":")).encode()
return base64.urlsafe_b64encode(raw).decode().rstrip("=")
def read_claims(token):
middle = token.split(".")[1]
middle += "=" * (-len(middle) % 4)
return json.loads(base64.urlsafe_b64decode(middle))
ISS = "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_EXAMPLE"
claims = {"iss": ISS, "sub": "u-42", "client_id": "app123", "exp": 1000, "token_use": "access"}
token = b64url({"alg": "RS256", "kid": "k1"}) + "." + b64url(claims) + ".sig"
seen = read_claims(token)
print("anyone can read:", seen["sub"], seen["client_id"])
for now in [990, 1010, 1020]: # exp = 1000, leeway = 15
leeway = 15
ok = seen["iss"] == ISS and seen["client_id"] == "app123" and now < seen["exp"] + leeway
print("now", now, "->", "200 OK" if ok else "401 Unauthorized")Complexity
- Time: O(1) per token: a fixed number of claim checks (plus one signature check)
- Space: O(1): only a short list of problems
Interview tips
Draw the path: Cognito → token → API Gateway authorizer → Lambda with a scoped IAM role → DynamoDB with KMS. Name one control per hop.
Expect 'how do you revoke a JWT?': short access-token lifetimes, revoke the refresh token (Cognito supports token revocation), and for emergencies a deny-list checked by a Lambda authorizer.
Expect 'where do you keep the DB password?': Secrets Manager, KMS-encrypted, read by one role, rotated automatically. Never in code or images.
Explain envelope encryption in four steps: GenerateDataKey, encrypt locally, keep only the encrypted key, Decrypt via KMS to read.
Mention the authorization bug interviewers love: the token says u-42, so the code must refuse /orders/991 if order 991 belongs to u-7.
Challenge: Validate JWT Claims
The signature has already been verified. Now check the claims.
Write jwt_problems(claims, now, issuer, audience, leeway) that returns a list of failing claim names, in this fixed order: "iss", "aud", "exp", "nbf". An empty list means the token is valid.
Rules:
- iss fails if
claims["iss"]is missing or not equal toissuer. - aud may be a string or a list of strings. It fails if
audienceis not that string / not in that list, or if aud is missing. - exp is required. It fails if missing, or if
now >= exp + leeway. - nbf is optional. It fails only if present and
now + leeway < nbf.
Example:
jwt_problems({"iss": "pool1", "aud": "app", "exp": 1000}, 1000, "pool1", "app", 0) -> ["exp"]
jwt_problems({"iss": "pool1", "aud": "app", "exp": 1000}, 1010, "pool1", "app", 30) -> []
Solve it in the browser with tests, hints and an AI coach.
Practice problems
- Verifying a Cognito JSON Web Token (AWS docs)
- Controlling access to HTTP APIs with JWT authorizers (AWS docs)
- AWS KMS concepts: envelope encryption (AWS docs)
- Design Authentication Manager (Medium)
More in Production in the Cloud
- Reliability: SLOs, Retries & Circuit Breakers
- Observability: Logs, Metrics & Traces
- AWS Well-Architected & Cost Optimization
- Choosing a Cloud: AWS vs GCP vs Azure vs Open Source
Previous: Observability: Logs, Metrics & Traces · Next: AWS Well-Architected & Cost Optimization