Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Authentication with Amazon Cognito

Clear, exam-focused notes on Amazon Cognito authentication: User Pools, Identity Pools, tokens, OAuth flows, SRP, role mapping, key CLI/SDK syntax, worked examples and common exam mistakes.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Amazon Cognito is an AWS service engineers use to add user sign-up, sign-in and access control to web and mobile apps without building an auth system from scratch. It integrates users (via User Pools), external identity providers, and AWS permissions (via Identity Pools) so apps can authenticate users and get short-lived AWS credentials securely.

Key ideas

  • User Pool — a managed user directory in Cognito. Definition: a user directory that stores user profiles (attributes) and performs sign-up, sign-in, password reset and token issuance. A User Pool issues JWT tokens to authenticated users.

    • Data stored: username, email, phone, custom attributes.
    • Supports built-in and custom attributes, account verification, multi-factor authentication (MFA) and Lambda triggers for custom flows.
  • Identity Pool (Federated Identities) — a mapping service that exchanges identities (from Cognito User Pools or external IdPs) for AWS temporary credentials. Definition: an entity that trusts identity tokens and returns AWS security credentials (IAM role-based) so the application can call AWS services.

    • Identity Pool connects an authenticated identity to one or more IAM roles.
    • It can also provide unauthenticated (guest) access by assigning an unauthenticated IAM role.
  • JWT (JSON Web Token) — a compact, URL-safe token format. Definition: a token with three Base64URL parts: header.payload.signature. The payload contains claims such as sub (user id), exp (expiry), iss (issuer), aud (audience). Draw exactly: a horizontal rectangle split into 3 labeled boxes: header | payload | signature. Label header: algorithm, type; payload: claims like sub, email, exp; signature: HMAC/RSA over header.payload.

  • Token types Cognito issues (definitions + purpose):

    • ID token — a JWT that contains user identity claims (who the user is). Use: present to the app for user info.
    • Access token — a JWT for authorizing calls to protected APIs (resource servers). Use: present in HTTP Authorization header as Bearer when calling APIs.
    • Refresh token — a long-lived opaque token used to obtain new ID and Access tokens without re-entering credentials.
  • OAuth 2.0 flows supported by Cognito (definitions):

    • Authorization code grant — client receives an authorization code via redirect, exchanges it (server-side) for tokens; secure for server-based apps. For public clients (SPAs and mobile), use Authorization Code with PKCE instead of Implicit.
    • Implicit grant — tokens returned directly in redirect URI; legacy and generally discouraged. Prefer Authorization Code with PKCE for SPAs; refresh tokens aren’t issued in this flow.
    • Client credentials — machine-to-machine flow (not tied to a specific user).
    • Resource Owner Password Credentials (ROPC) — not supported by Cognito’s OAuth 2.0 endpoints; use SRP/USER_PASSWORD_AUTH via AWS SDKs instead (collect passwords only in trusted first‑party clients).
  • SRP (Secure Remote Password) — a zero-knowledge password proof protocol. Definition: a cryptographic protocol where the client proves knowledge of a password to the server without sending the password. Cognito SDKs implement SRP for USER_SRP_AUTH flow so plaintext passwords do not travel over the network.

  • Lambda triggers — events where Cognito invokes an AWS Lambda function to customize behaviour (pre-signup, post-confirmation, pre-token generation, etc.). Definition: server-side callbacks that extend Cognito flows.

  • Role mapping — the rule set in an Identity Pool that selects which IAM role to assume based on token claims (for example, group membership claim). Exact statement: when Cognito Identity issues AWS credentials, it picks an IAM role by evaluating the mapping rules (authenticated vs unauthenticated, and optionally rules on token claims like 'cognito:groups').

  • Token validation (exam-style exact steps): to validate a JWT issued by Cognito do the following:

    1. Verify the token is well-formed (three parts).
    2. Verify iss (issuer) equals the expected Cognito issuer URL (https://cognito-idp.<region>.amazonaws.com/<userPoolId>).
    3. For an ID token, verify aud equals your app client id and token_use is id. For an access token, verify token_use is access and client_id equals your app client id (Cognito access tokens don’t include aud). If you use custom resource servers, also verify that the scope claim includes the required scope(s).
    4. Verify exp (expiry) is in the future.
    5. Verify signature using the Cognito JSON Web Key Set (JWKS) fetched from the issuer's /.well-known/jwks.json endpoint.

Assumptions: network access to JWKS endpoint, system clock correct (for exp check).

Formulas

List of important syntax and short rules to remember (each line is a separate syntax item): JWT = header.payload.signature — header and payload Base64URL encoded, signature = Sign( header + '.' + payload, key ) Authorization: Bearer <access_token> — HTTP header to present Access token for APIs aws cognito-idp create-user-pool --pool-name <name> — AWS CLI create user pool aws cognito-idp create-user-pool-client --user-pool-id <id> --client-name <name> --no-generate-secret — CLI create a user-pool client for browser apps aws cognito-identity create-identity-pool --identity-pool-name <name> --allow-unauthenticated-identities — CLI create identity pool boto3.client('cognito-idp') and boto3.client('cognito-identity') — Python SDK clients cognito-idp.initiate_auth(ClientId=..., AuthFlow='USER_SRP_AUTH', AuthParameters={...}) — start SRP flow (boto3) cognito-identity.get_id(AccountId=..., IdentityPoolId=..., Logins={provider: token}) — get identity id (boto3) cognito-identity.get_credentials_for_identity(IdentityId=..., Logins={...}) — obtain AWS temporary credentials (boto3)

Worked examples

Example 1 — Basic sign-in using a User Pool (step-by-step trace) Given: a User Pool with id us-east-1_EXAMPLE, App Client id: 1abc234defgh567iop (no client secret), user: alice@example.com with password "P@ssw0rd" Steps and expected calls:

  1. Client app calls Cognito sign-in SDK which uses SRP: initiate_auth with AuthFlow='USER_SRP_AUTH' and username. Server returns challenge parameters (salt, srpB) and a SECRET_BLOCK.
  2. Client computes SRP proof (using password and challenge) and calls respond_to_auth_challenge with proof.
  3. If correct, Cognito returns tokens: IdToken (JWT), AccessToken (JWT), RefreshToken (opaque). Example fields in IdToken payload: sub = user unique id, email = alice@example.com, iss = https://cognito-idp.us-east-1.amazonaws.com/us-east-1_EXAMPLE, exp = 1610000000.
  4. Client stores tokens securely (in memory or secure storage) and sends Authorization: Bearer <AccessToken> when calling protected APIs. Final: The app has user identity (IdToken) and can call AWS resources via Identity Pool if needed.

Example 2 — Federated login with Google and obtaining AWS credentials Scenario: Mobile app uses Google Sign-In and wants to call S3 via temporary credentials.

  1. Mobile app obtains Google ID token from Google Sign-In SDK.
  2. App calls Cognito Identity GetId with Logins map: { "accounts.google.com": "<Google ID token>" } and the IdentityPoolId.
  3. Cognito Identity returns an IdentityId (like us-east-1:1234abcd-...).
  4. App calls GetCredentialsForIdentity(IdentityId, Logins).
  5. Cognito evaluates role mapping and returns temporary AWS credentials (AccessKeyId, SecretKey, SessionToken) associated with the IAM role mapped for authenticated Google users.
  6. App uses returned temporary credentials to sign AWS API calls (for example, to S3). Steps 2–5 are the exact sequence to draw if asked in an exam diagram: draw client -> Cognito Identity (GetId) -> Cognito Identity (GetCredentialsForIdentity) -> AWS temporary credentials -> AWS Service.

Example 3 — Token validation (theory question model answer) Question: Explain how a backend API should validate a Cognito Access token. Model answer steps: (1) Parse JWT into header/payload/signature; (2) Fetch JWKS from issuer URL; (3) Verify signature using matching JWK kid; (4) Verify exp not expired; (5) For an access token, verify token_use is access and client_id equals your app client id (Cognito access tokens don’t include aud). For an ID token, verify aud equals your app client id; (6) Verify scopes claim contains required scope for the endpoint; (7) If all pass, accept request and use claims (sub, username) for authorization decisions.

Common mistakes

  • Not validating the JWT signature and only trusting aud or iss checks.
  • Storing tokens unsafely (localStorage without extra protection in SPAs). Always use secure storage and follow least-privilege.
  • Expecting client credentials (App client secret) to be safe in browser apps — do not place secrets in public clients.
  • Assuming Cognito will auto-create IAM policies — Cognito only selects IAM roles, you must attach precise policies.
  • Forgetting to update CORS and callback URLs for the Hosted UI leading to redirect failures.

For your exam

Typical question types:

  • Definitions and short notes: Define User Pool / Identity Pool / JWT / SRP. Include short exam-style examples of where each is used.
  • Diagram: Draw flow of obtaining AWS credentials using a federated login (label HTTP calls: GetId, GetCredentialsForIdentity and the tokens passed in Logins map).
  • Derivation / Step list: Steps to validate a JWT from Cognito (as in Worked example 3) — give exact checks and order.
  • Small program: Show AWS CLI or boto3 sequence to create user pool, client and sign a user in (pseudo-code is acceptable). A full-marks answer shows command names and key parameters.
  • Troubleshooting short note: Why would an API return 401 for a valid-looking token? (Answers: wrong issuer, expired token, signature verify failed, wrong audience/scopes.)

What full-marks answers include:

  • Precise definitions (bold if required), exact sequence of steps, mention of token fields (iss, aud, exp), and security considerations (validate signature, secure storage of tokens).

Quick check

  1. Which Cognito feature issues JWT tokens: User Pool or Identity Pool?
  2. What HTTP header and format should you use to send an access token to an API?
  3. Name the two Cognito API calls used to obtain AWS temporary credentials for a federated identity. Answers: User Pool; Authorization: Bearer <access_token>; GetId and GetCredentialsForIdentity

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?