Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

FastAPI
  • FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
  • RESTful API Basics: Resources, Methods, Stateless Requests and Status Codes
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Backend vs Frontend: What Runs Where, and Why the Server Is the One You Trust
  • One Request, Two Answers: the Same Post as an HTML Page and as JSON
  • What FastAPI Is: Starlette, Pydantic, uvicorn and What async def Really Gives You
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a FastAPI Blog: Every Folder and File an AI Agent Built, and What to Question
  • Swagger UI and OpenAPI in FastAPI: Reading the Contract Your Code Writes
  • POST, PUT and DELETE in FastAPI: Choosing 201, 200, 204 and 404 on the Server
  • Paging, Sorting and Filtering a REST API in FastAPI
  • File Upload and Download in FastAPI: multipart, UploadFile and FileResponse
  • API Versioning in FastAPI with an API-Version Header
  • Idempotent REST Methods, HATEOAS and the Maturity Model: Which Requests Are Safe to Repeat
  • A FastAPI REST API End to End: One App Visit, Seven Requests
  • The Book API in FastAPI: A Contract a React Client Can Rely On
  • A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
  • Dependency Injection With FastAPI Depends: Providers, dependency_overrides and yield
  • A Layered FastAPI Project: Controllers, Services, Schemas and One Folder per Concern
  • FastAPI Request and Response Models with Pydantic: Design the JSON on Purpose
  • FastAPI Path, Query and Body Parameters: Reading a 422, response_model and Depends
  • Validation and Problem Details in FastAPI: From a 422 to One Error Shape for the Whole API
  • FastAPI with SQLAlchemy Models and Alembic Migrations: A Table from a Class, a Session per Request
  • From a List to a Database in FastAPI: Route, Service, Repository and the SQL SQLAlchemy Sends
  • Docker Compose: Run a FastAPI App and Postgres From One File
  • Docker Health Checks, Networks and Resource Limits: Up Is Not Enough
  • Repository and Unit of Work With SQLAlchemy: Both Writes or Neither, and a Test With No Database
  • How a Request and a Login Flow Through a FastAPI Blog: Depends, bcrypt, a Signed Session Cookie and async def
  • An Auth Starter Kit with Keycloak: Build Sign In Once, Put the Backend Between React and the Identity Provider
  • Protecting a Python API with Keycloak: Check the JWT Signature, Issuer and Expiry in FastAPI, Django and Flask
  • How an Identity Provider Login Works: The OpenID Connect Code Flow vs a Backend Password Grant, with Keycloak
  • AWS Cognito vs Keycloak: User Pools, App Clients and When a Managed Identity Provider Wins
  • Migrating FastAPI from Keycloak to AWS Cognito: The Four Values, the JWKS Address and Every Check on an Access Token
  • Testing a Cognito Login End to End: Allow the Password Flow, Confirm the Email Code, and Reset a Forgotten Password
  • Enterprise Integration for an AI App: One Adapter per Edge for SSO, the CRM, a Legacy CSV and Webhooks
  • Testing a FastAPI Blog with pytest: a Test Database through dependency_overrides, Login Fixtures and Reading a Failure
  • Smoke-Testing a Dockerized LLM App by Hand: Stage the Weights, Check Every Layer, Make Errors Say Why
  1. Blog
  2. /
  3. FastAPI
  4. /
  5. Authentication

Migrating FastAPI from Keycloak to AWS Cognito: The Four Values, the JWKS Address and Every Check on an Access Token

Move the backend's login from Keycloak to a Cognito user pool. Create the pool and app client, collect four values (region, pool ID, client ID, client secret), build the issuer and JWKS address from them, and check every access token for its key, issuer, token_use and client. Login goes through boto3 with a SECRET_HASH.

Chaand Sheikh

·27 November 2026·Updated 29 November 2026Authentication

What you will learn

  • Create a Cognito user pool and app client and collect the four values the backend needs
  • Build the issuer and JWKS address from the region and pool ID
  • Verify a Cognito access token: key ID, RS256, expiry, issuer, token_use and client ID
  • Sign users in with boto3 and a SECRET_HASH, and know what else changes in the move

Before you start

  • AWS Cognito vs Keycloak
  • Protecting a Python API with Keycloak

The front end talks only to the FastAPI backend, and that doesn't change. Before, the backend asked a Keycloak container on localhost port 8080 to log people in and check tokens. Now that job moves to a Cognito user pool that AWS runs. So the issuer changes from the Keycloak realm address to a Cognito address built from the region and the user pool ID. The routes (register, login, logout and me) keep their paths. Only the code behind them changes.

The coding agent's summary said only three values were required: the AWS region, the user pool ID and the app client ID. Keep that in mind, because the console shows a fourth.

Create the pool and the app client

In the AWS console, open Cognito and click "get started for free in less than five minutes". This sets up the user pool and the app client together.

  1. Pick traditional web application and name it (here, studyeasy).
  2. Tick email as the sign in identifier.
  3. Keep enable self-registration ticked, so new users can sign up from the app.
  4. Read the warning: sign in options can't be changed after the app is created.
  5. Keep the rest as default and click create. Cognito shows sample code, which you can ignore; the backend has its own.

Collect four values

ValueWhere
RegionThe region list in the top bar. The pool here was in Stockholm, code eu-north-1
User pool IDThe user pool overview, next to the token signing key URL
App client IDApp clients, then your client
Client secretJust below it, behind show client secret

A traditional web application client gets a secret, so you need the fourth value even though the guide said three. Treat the secret like a password: keep it out of git and out of screenshots.

In the IDE, create .env at the project root and copy sample.env into it. The sample has eu-west-2, which didn't match this pool, so that's the line to fix. Your file looks like this, with your own values:

AWS_REGION=<your-region>
COGNITO_USER_POOL_ID=<your-user-pool-id>
COGNITO_APP_CLIENT_ID=<your-app-client-id>
COGNITO_APP_CLIENT_SECRET=<your-app-client-secret>

The AWS access key lines stay commented out; you'll see why below. The empty keycloak folder the agent left behind can be deleted.

The issuer and the keys address

In config.py, the settings class reads the region and pool ID from .env (it looks in its own folder and one level up, so the file at the project root is found) and glues them together:

    aws_region: str = "eu-west-2"
    cognito_user_pool_id: str = ""
    cognito_app_client_id: str = ""
    cognito_app_client_secret: str | None = None
    cognito_auth_flow: str = "USER_PASSWORD_AUTH"
    cognito_token_use: str = "access"
    cognito_groups_claim: str = "cognito:groups"
    cognito_auto_confirm_sign_up: bool = False

    @property
    def cognito_issuer(self) -> str:
        if self.cognito_issuer_override:
            return self.cognito_issuer_override.rstrip("/")
        return (
            f"https://cognito-idp.{self.aws_region}.amazonaws.com/"
            f"{self.cognito_user_pool_id}"
        )

    @property
    def cognito_jwks_url(self) -> str:
        if self.cognito_jwks_url_override:
            return self.cognito_jwks_url_override
        return f"{self.cognito_issuer}/.well-known/jwks.json"

The JWKS address is the issuer plus /.well-known/jwks.json, the same token signing key URL shown in the console. Leave the region at eu-west-2 while the pool lives in eu-north-1, and the issuer points at the wrong place, so no token would ever pass. The pool ID itself starts with its region, which is an easy way to check.

Checking a Cognito token

With Keycloak, a library did this. Now the code in cognito.py does it step by step.

Five checks on a Cognito access token key by kid refetch once RS256 signature, expiry issuer token_use must be access client_id our app client signing key not found signature has expired invalid issuer invalid token_use: id invalid Cognito app client each failure is a 401
A valid signature isn't enough. The last two checks are the ones Keycloak didn't need.

Find the key

def _find_jwk(token: str) -> dict[str, Any]:
    try:
        header = jwt.get_unverified_header(token)
    except JWTError as exc:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid token header",
            headers={"WWW-Authenticate": "Bearer"},
        ) from exc

    kid = header.get("kid")
    jwks = _load_jwks()
    for key in jwks.get("keys", []):
        if key.get("kid") == kid:
            return key

    jwks = _load_jwks(force_refresh=True)
    for key in jwks.get("keys", []):
        if key.get("kid") == kid:
            return key

    raise HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Token signing key not found",
        headers={"WWW-Authenticate": "Bearer"},
    )

It reads the token's header and takes the kid, the ID of the key that signed it. _load_jwks keeps Cognito's public keys for an hour (_jwks_ttl_seconds = 3600). If the kid isn't in the list, it fetches once more in case the keys rotated. Still missing means 401.

Decode, then check what kind of token it is

def decode_token(token: str) -> dict[str, Any]:
    key = _find_jwk(token)
    try:
        claims = jwt.decode(
            token,
            key,
            algorithms=["RS256"],
            issuer=settings.cognito_issuer,
            options={"verify_aud": False},
        )
    except JWTError as exc:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=f"Invalid or expired token: {exc}",
            headers={"WWW-Authenticate": "Bearer"},
        ) from exc

    token_use = claims.get("token_use")
    if token_use != settings.cognito_token_use:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=f"Invalid token_use: {token_use}",
            headers={"WWW-Authenticate": "Bearer"},
        )

    client_id = claims.get("client_id") or claims.get("aud")
    if client_id != settings.cognito_app_client_id:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid Cognito app client",
            headers={"WWW-Authenticate": "Bearer"},
        )

    return claims

jwt.decode checks the RS256 signature, the expiry and the issuer. An expired token gets "Signature has expired", and a token from another pool gets "Invalid issuer". Then come the Cognito-specific checks. Cognito gives out two kinds of token, an ID token and an access token, and this API wants access tokens only, so token_use must be access; send an ID token and you get "Invalid token_use: id". The client ID inside the token must match your app client, or it's "Invalid Cognito app client". When everything matches, /auth/me answers 200 with the user's sub. With no token at all, FastAPI answers 401, not authenticated, before this code runs.

Login, sign up and logout with boto3

The Keycloak library is gone. The backend uses boto3, the AWS SDK for Python, against the cognito-idp client. Login calls initiate_auth with the flow USER_PASSWORD_AUTH, which the app client must allow. Because the client has a secret, every call also sends a secret hash:

def _secret_hash(username: str) -> str | None:
    secret = _client_secret()
    if not secret:
        return None
    digest = hmac.new(
        secret.encode("utf-8"),
        f"{username}{settings.cognito_app_client_id}".encode("utf-8"),
        hashlib.sha256,
    ).digest()
    return base64.b64encode(digest).decode("utf-8")

It's an HMAC with SHA-256 of the username plus the client ID, keyed with the client secret, then base64 encoded. That's why the secret had to go into .env. Sign up calls sign_up with the email as the username, and Cognito says whether the user is confirmed. Logout calls revoke_token on the refresh token. These calls only need the app client, not AWS access keys, which is why the key lines stay commented out.

What else changed

KeycloakCognito
Rolesrealm_access.rolesThe groups claim, cognito:groups
Usernamepreferred_usernameusername or cognito:username
requirements.txtpython-keycloakboto3
docker-compose.ymlKeycloak service and realm importRemoved; the backend gets the region and Cognito values
Front end tokensAccess and refreshAlso the ID token

There's one new case on the front end. When the pool asks new users to confirm their account, sign up answers with confirmed: false, so the page shows "User registered. Confirm the account before logging in" instead of going straight to the dashboard. That flow is in testing the Cognito migration.

Common mistakes

  • A region in .env that isn't the pool's region.
  • Accepting ID tokens as API tokens. Check token_use.
  • Skipping the client ID check, so tokens from another app client in the same pool get in.
  • Forgetting the secret hash on a client that has a secret.

Quick recap

  • Four values from the console: region, user pool ID, client ID, client secret.
  • Issuer and JWKS address are built from the region and the pool ID.
  • Every token is checked for its key, signature, expiry, issuer, token use and client.

Try it yourself

Open your user pool overview and check that its token signing key URL matches the JWKS address your config builds.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in FastAPI · 35 of 39

Previous
AWS Cognito vs Keycloak: User Pools, App Clients and When a Managed Identity Provider Wins
Next post
Testing a Cognito Login End to End: Allow the Password Flow, Confirm the Email Code, and Reset a Forgotten Password

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Related posts

How a Request and a Login Flow Through a FastAPI Blog: Depends, bcrypt, a Signed Session Cookie and async def

Follow GET / through the FastAPI blog to two SQL statements and an HTML page, then a login: one SELECT, a bcrypt check, a 303 with a signed session cookie that decodes to user_id 1. A changed cookie gets 401, a plain user 403, and three slow requests on async def with a blocking session finish at 1.92 s while a ping waits 1.83 s.

An Auth Starter Kit with Keycloak: Build Sign In Once, Put the Backend Between React and the Identity Provider

Almost every project needs sign in, sign out and a token check, so build them once in a starter kit. Tour the kit's four pillars, then finish it: a fix prompt, a backend that sits between React and Keycloak with register, login, me and logout routes, and the limits of a stateless access token.

Protecting a Python API with Keycloak: Check the JWT Signature, Issuer and Expiry in FastAPI, Django and Flask

Keycloak signs the access token; your API only checks it. Run Keycloak in Docker with a realm file, fetch its public keys once, check RS256, the issuer and the expiry, and protect /api/me with one Depends. Then the same check as a Django REST framework class and a Flask decorator.

How an Identity Provider Login Works: The OpenID Connect Code Flow vs a Backend Password Grant, with Keycloak

What an identity provider does, the four Keycloak words you see everywhere, the standard OpenID Connect sign in (redirect, code, token), and the custom-page version where FastAPI sends a password grant. Then one token followed from login to the check, plus refresh, logout and dev mode.

On this page

  • Create the pool and the app client
  • Collect four values
  • The issuer and the keys address
  • Checking a Cognito token
  • Find the key
  • Decode, then check what kind of token it is
  • Login, sign up and logout with boto3
  • What else changed
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.