Ravindra BagaleCourses & study guides मराठी Track your progress

AWS Cloud

What Is Amazon Cognito? User Pools and Identity Pools Explained

Your React app needs sign-up, login, MFA, and temporary AWS credentials to upload to S3 — without you building a custom auth server. Amazon Cognito gives User Pools (directory + tokens) and Identity Pools (federate to AWS IAM credentials).

In this chapter

  • Why managed auth beats home-grown password DBs
  • What user pools vs identity pools are
  • How JWT app clients and IdPs fit together
  • Industries and mobile/web patterns
  • Lab, errors, FAQ, interview

1. Everyday example first

A Kochi fitness app lets users sign in with email+OTP or Google. Cognito User Pool issues JWT. An Identity Pool exchanges the token for short-lived IAM rights to PutObject into s3://app-uploads/userId/*. API Gateway JWT authorizer protects /workouts.

2. Why Cognito?

Password storage, reset flows, MFA, and token crypto are easy to get wrong. Cognito provides standards-based auth (OAuth2/OIDC) and hooks into AWS IAM for fine-grained data access.

  • Hosted UI or own UI with SDKs
  • Social and SAML/OIDC enterprise IdPs
  • JWT for APIs
  • Identity Pool → temporary AWS credentials

Choose the credential for the destination

Calling your course API and calling the S3 API directly are different requests. Cognito provides different outputs for these paths.

Choose the credential for the destinationUser pool sign-in: Returns signed user tokens; Course API path: Access token; API checks permissions; Identity pool path: Returns temporary AWS credentials; Direct AWS API call: IAM role limits allowed operationsUser pool sign-inReturns signed user tokensCourse API pathAccess token; API checks permissionsIdentity pool pathReturns temporary AWS credentialsDirect AWS API callIAM role limits allowed operations
Read all steps
  1. Sign in to the application

    The user authenticates through the configured user pool flow. The application receives signed tokens. The token identifies claims about the sign-in; it is not a permanent AWS access key.

  2. Call the course API

    For an API designed to accept access tokens, the client sends the token and the API verifies it and the required scopes. The application must also check whether this user may access the specific course record.

  3. Use an identity pool only when the design needs it

    An identity pool can use an accepted identity to obtain temporary AWS credentials for an allowed role. That is useful when the client needs to call an AWS API directly. Many applications only need the user-pool-plus-API path.

  4. Limit the AWS request

    For a direct S3 upload, the temporary role permissions should permit only the intended operations and object location. Successful sign-in alone does not authorise every bucket or every action.

3. What are User Pools and Identity Pools?

Imagine a student signs in to a course app. A user pool can manage sign-in and issue signed tokens. A token is a set of claims the app can verify, such as which user signed in or which requested permissions are granted. An identity pool can let an authenticated identity obtain temporary AWS credentials for a role. Draw two paths: sign-in to call your app’s API and temporary credentials to upload directly to a permitted S3 location. A project can use the first path without needing the second.

User Pool = user directory: sign-up, sign-in, MFA, groups, app clients, hosted UI; issues JWTs for ID and access. A refresh token is a separate credential used to obtain fresh tokens. Identity Pool (Federated Identities) = map authenticated (or guest) users to IAM roles via STS — for AWS resource access.

PiecePlain job
User poolAuthN directory + tokens
App clientPublic/confidential client settings
Hosted UIReady login pages
Identity poolToken → IAM role credentials
JWT authorizerAPI Gateway validates Cognito tokens
TriggersLambda customize sign-up/auth challenges
Keep application sign-in and AWS access distinctUser pool: Issues tokens after user authentication; Application or API: Validates tokens and authorises actions; Identity pool, if needed: Exchanges identity for AWS credentials; IAM role permissions: Limit the permitted AWS API callsUser poolIssues tokens after userauthenticationApplication or APIValidates tokens and authorisesactionsIdentity pool, if neededExchanges identity for AWScredentialsIAM role permissionsLimit the permitted AWS API calls
Authorized API & S3

4. How to wire a safe app client

An API needs to verify the token and decide whether the call is allowed. Think of the ID token as evidence about the signed-in user and the access token as evidence about the access granted to the client. For a lab API route, use a scope such as permission to read orders, and keep the API’s check of which order belongs to the user separate. On paper or in the lab, compare an allowed request with an expired token and one lacking the right scope. A visible login page alone does not answer the API’s permission question.

  1. Create a user pool with strong password policy + MFA optional/required as needed.
  2. Create an app client; for public SPAs use PKCE; never embed client secrets in mobile/SPA.
  3. Configure callback/logout URLs tightly.
  4. Enable Google/Apple/SAML only after privacy review.
  5. Protect APIs with a JWT authorizer or ALB authentication. For a JWT route that reads orders, require your API’s orders/read scope. Sign in with a lab client that has that scope and try the request with its access token. Then send the ID token from the same login and confirm the route rejects it.
  6. If S3 upload needed, Identity Pool roles with prefix-by-sub IAM.
  7. Use groups/custom claims carefully; authorize on server.
  8. Rotate refresh token strategy; handle revoke on logout.
  9. Log Advanced Security / Compromised credentials features if available.
  10. Never use Cognito only on client without API checks.
# Mental model
# 1) User Pool authenticates → JWT
# 2) API Gateway JWT authorizer checks iss/aud/exp
# 3) Optional: Identity Pool GetCredentialsForIdentity → S3 PutObject

5. User pool vs identity pool vs IAM Identity Center

ChoiceWhen
Cognito user poolCustomer/app users AuthN
Cognito identity poolAWS creds for app users
IAM Identity CenterWorkforce SSO into AWS accounts
Amazon Verified PermissionsFine-grained authZ policies (Cedar)

6. Multi-industry notes

EdTech apps use Cognito for millions of students with social login. Hospitals integrate SAML IdP for clinicians but still Cognito for patient apps. Fintech adds MFA mandatory and device tracking.

7. Industries and roles

  • Mobile/web startups: fast auth
  • EdTech: social + email OTP
  • Healthcare: SAML workforce + patient pools
  • Fintech: MFA + risk
  • API developers: JWT authorizers

8. Lab: user pool + Hosted UI sample

Use a dummy account. Check that the exact callback URL returns you to the lab app and that the test API returns its expected result with an authorized access token. Attempt the check with an expired token or one missing the required scope and expect the configured deny response. Keep full tokens out of your lab log. Remove the disposable client, user, and pool afterward where appropriate.

Do this in ap-south-1 (Mumbai) unless your org forbids it. Set a budget alert first.

  1. Create a user pool with email sign-in in ap-south-1.
  2. Create a public app client for your running local sample app and register its exact callback URL. For a lab app serving plain HTTP on localhost port 3000, use http://localhost:3000/callback. Choose authorization code with PKCE for the public client.
  3. Enable Hosted UI; create a test user; sign in; inspect JWT claims carefully offline (lab token).
  4. Optional direct upload test. Map the identity pool to an authenticated lab role that allows s3:PutObject only on the approved sample prefix. Verify the permitted upload and an out-of-prefix denial with harmless data.
  5. For the API test, configure a JWT authorizer with the user pool issuer and the audience your lab expects. On an existing disposable HTTP API, attach it to the test route and require the configured custom scope. Confirm the authorized access token reaches the route and one missing the scope is rejected.

Cleanup (stop billing)

  1. Remove disposable API test routes and authorizers, test users, the app client and the user pool. If you ran the optional direct S3 upload test, remove the lab identity pool, its lab role and the sample objects.
  2. Remove lab callback URLs from any reused pools.

9. Common errors and fixes

Each row is a real mistake students and juniors hit. Read the fix before you panic.

Error / symptomFix
Client secret in React bundlePublic client + PKCE; secrets only confidential apps.
Callback URL *Exact URLs only.
Trusted JWT on client onlyAlways verify on API.
Identity Pool role = AdministratorAccessPrefix-scoped least privilege.
Confused user pool with identity poolAuthN tokens vs AWS creds.
Disabled token revocation thinkingHandle logout/refresh carefully.
MFA off for finance appTurn on MFA.
Custom UI missing error handling for USER_PASSWORD_AUTH flowsHandle challenges.
PII in custom attributes without consentPrivacy review.
Long-lived access tokensShort exp + refresh.

10. Troubleshooting checklist

  1. Invalid redirect: callback mismatch.
  2. Unauthorized client: app client auth flows mis-set.
  3. CORS issues on Hosted UI/API: configure properly.
  4. Identity Pool no credentials: role trust / claim mapping.
  5. API 401: audience/issuer mismatch.
  6. Email delivery for OTP: SES sandbox limits.

11. FAQ

Q. Cognito free?

MAU pricing; free tier exists — check current.

Q. Replace Auth0/Firebase?

Comparable space; evaluate features/TCO.

Q. Offline mobile?

Refresh/session design; not magic offline auth.

Q. SAML enterprise?

Supported federation into user pools.

Q. Guest access?

Identity Pool unauthenticated role — tight limits.

Q. Passwordless?

Custom auth / features evolving — verify docs.

12. Interview Q&A

Q. User pool vs identity pool?

User pool=AuthN/JWT; identity pool=AWS IAM creds.

Q. What is JWT here?

Signed token APIs validate for identity/scopes.

Q. PKCE?

Protect public clients during auth code flow.

Q. Hosted UI?

Cognito-managed login pages.

Q. Secure S3 upload pattern?

Identity Pool role limited to user prefix.

Q. Workforce vs customer auth?

IDC for workforce; Cognito often customer apps.

13. Tips in English, Marathi and Hindi

Ravindra Bagale's Tip (EN)

Never ship a Cognito client secret inside a mobile or SPA binary. Public client + PKCE, and authorize on the server.

Ravindra Bagale's Tip (MR)

Mobile/SPA मध्ये client secret नका. Public+PKCE; server authorize.

Tip (HI)

मोबाइल/SPA में client secret मत डालो — public+PKCE और server पर authorize।

Try at home

  1. Draw user pool → JWT → API Gateway on paper.
  2. Write an IAM policy sketch: s3:PutObject on private/user-sub prefix.
  3. List three callback URL mistakes.

In short

  1. User pools authenticate users and issue JWTs.
  2. Identity pools exchange identity for IAM credentials.
  3. PKCE for public apps; verify JWT on APIs.
  4. Least-privilege roles for uploads.

Revision, interview and comparison cards

Revise this lesson in a few minutes. Save the cards on your phone or download them as PNG files. The QR code on each card opens this lesson.

Revision card: Cognito user and identity pools. Building your own auth (passwords, MFA, tokens) is slow and risky. User pools authenticate users (sign-up/sign-in/MFA/JWT). Identity pools can issue temporary AWS credentials. Create user pool + app client → host UI or SDK → validate JWTs on API; optional identity pool for S3 uploads. Mobile app signs in via user pool; gets scoped creds to upload to one S3 prefix.
Revision card: Cognito user and identity pools · Download PNG · Open card page
Revision card: Validate JWTs. Trusting a token without verifying signature/claims invites impersonation. APIs must verify issuer, audience, signature (JWKS), and expiry on Cognito access/ID tokens. Use API Gateway Cognito authorizer or verify in app middleware; never skip in “just for now”. Expired token → 401; wrong aud → reject even if signature looks fine.
Revision card: Validate JWTs · Download PNG · Open card page
Comparison: User pool vs Identity pool. User pool: Sign-up/sign-in/MFA/JWT for your app users. Identity pool: Federated identities → temporary AWS credentials.
Comparison: User pool vs Identity pool · Download PNG · Open card page
Comparison: JWT access token vs Server session cookie. JWT access token: Stateless bearer verified via JWKS; good for APIs/SPAs. Server session cookie: Server stores session; classic websites.
Comparison: JWT access token vs Server session cookie · Download PNG · Open card page
Interview card: User pool vs identity pool?. User pool authenticates users (JWT). Identity pool can exchange identity for temporary AWS credentials. Many apps need only a user pool + API JWT check. Sign-in JWT to API Gateway; identity pool for direct S3 upload.
Interview card: User pool vs identity pool? · Download PNG · Open card page
Interview card: Why enforce MFA?. Password-only accounts fall to phishing/stuffing; MFA raises the bar. Prefer TOTP/WebAuthn over SMS when possible. Admin console requires MFA ON for all users.
Interview card: Why enforce MFA? · Download PNG · Open card page
Interview card: What must you verify on a JWT?. Signature (JWKS), issuer, audience, expiry (and token_use as applicable). Never trust claims without verification. API Gateway Cognito authorizer handles checks.
Interview card: What must you verify on a JWT? · Download PNG · Open card page
Interview card: Public vs confidential app client?. Public (mobile/SPA) has no client secret; confidential (server) can use a secret. Use PKCE for public clients. React SPA = public+PKCE; backend = confidential.
Interview card: Public vs confidential app client? · Download PNG · Open card page

More cards: Ravi Sir's Cards.

Practise this chapter

Interview questions and answers

A student can sign in but the order API refuses the request. How do you diagnose this?

Check whether the request uses the intended access token, then verify issuer, expiry, audience or client and scopes. If the token passes, check whether that student can access the selected order. A successful sign-in gives identity evidence; the API still enforces permission for the action.

Check your understanding

Choose an answer, then compare your reasoning with the explanation.

0 of 3 answered correctly
1. What can a Cognito user pool issue after sign-in?

Answer and explanation

A. Signed tokens containing identity or access claims

User pools authenticate users and issue tokens. Obtain temporary AWS credentials through the separate identity pool path when needed.

2. Which component can provide temporary role credentials for a direct permitted S3 upload?

Answer and explanation

A. An identity pool configured to grant the allowed role

An identity pool can map an identity to role credentials with limited AWS permissions.

3. What is a good negative test of an API route’s scope requirement?

Answer and explanation

A. Send a test token lacking that required scope and verify a denial

A deliberately missing scope proves that the check rejects a request without the grant.

Practice Tasks

Practice checks run in your browser. They check the answer for this exercise; they do not create resources or connect to your AWS account.

About this scenario

Nairobi Ride is a transport business in Nairobi. Wanjiru Kamau looks after its IT and cloud work. They count money in KES and run their AWS resources in the af-south-1 Region. In the tasks below you do real jobs for them using what this lesson teaches. All names, account IDs, IP addresses and numbers are made up for practice.

0 / 16

Easy List user pools

Auth inventory.

List user pools.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Easy Describe user pool

MFA/password.

Describe user pool nairobiridepool.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Easy List resource servers

Scopes.

List resource servers for nairobiridepool.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Easy Apply the lesson: scenario 4

You need sign-up, sign-in and user tokens. Which Cognito feature fits: user pool or identity pool?

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Easy Apply the lesson: scenario 5

An authenticated client needs temporary AWS credentials for permitted AWS APIs. Which Cognito feature is designed for that exchange?

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Medium List user pool clients

App clients.

List user pool clients for nairobiridepool.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Medium List groups

Authorization.

List groups in nairobiridepool.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Medium List identity pools

AWS creds.

List identity pools.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Medium Allow GetId identity pool

Mobile LP.

Allow cognito-identity:GetId on arn:aws:cognito-identity:af-south-1:104591109902:identitypool/nairobirideidpool.

  1. Start with { "Version": "2012-10-17", "Statement": [ ... ] }.
  2. In each statement write Effect, Action and Resource.
  3. Give only what the task needs (least privilege).
  4. Use double quotes and commas correctly. Click Check answer.

Medium MFA required JSON

Security.

JSON MfaConfiguration ON.

  1. Start from the top-level keys the task names.
  2. Indent child keys with 2 spaces (no tabs).
  3. Fill in each property with the value from the task.
  4. Click Check answer. Key order does not matter.

Medium Apply the lesson: scenario 11

An API receives a Cognito JWT. Is decoding its payload alone sufficient, or must the API validate it? Answer decode or validate.

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Medium Sample access token minutes

Token life.

Sample access token minutes often used (enter 60)?

  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Hard List identity providers

Federation.

List identity providers for nairobiridepool.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Hard List users

Directory.

List users in nairobiridepool.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Hard Allow AdminGetUser

Support LP.

Allow cognito-idp:AdminGetUser on arn:aws:cognito-idp:af-south-1:104591109902:userpool/nairobiridepool.

  1. Start with { "Version": "2012-10-17", "Statement": [ ... ] }.
  2. In each statement write Effect, Action and Resource.
  3. Give only what the task needs (least privilege).
  4. Use double quotes and commas correctly. Click Check answer.

Hard Auth flows JSON

SRPA.

JSON ExplicitAuthFlows USER_SRP_AUTH.

  1. Start from the top-level keys the task names.
  2. Indent child keys with 2 spaces (no tabs).
  3. Fill in each property with the value from the task.
  4. Click Check answer. Key order does not matter.