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.
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.
- Pick traditional web application and name it (here, studyeasy).
- Tick email as the sign in identifier.
- Keep enable self-registration ticked, so new users can sign up from the app.
- Read the warning: sign in options can't be changed after the app is created.
- Keep the rest as default and click create. Cognito shows sample code, which you can ignore; the backend has its own.
Collect four values
| Value | Where |
|---|---|
| Region | The region list in the top bar. The pool here was in Stockholm, code eu-north-1 |
| User pool ID | The user pool overview, next to the token signing key URL |
| App client ID | App clients, then your client |
| Client secret | Just 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.
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
| Keycloak | Cognito | |
|---|---|---|
| Roles | realm_access.roles | The groups claim, cognito:groups |
| Username | preferred_username | username or cognito:username |
| requirements.txt | python-keycloak | boto3 |
| docker-compose.yml | Keycloak service and realm import | Removed; the backend gets the region and Cognito values |
| Front end tokens | Access and refresh | Also 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
.envthat 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.
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.
