Why Teams Move From Keycloak to AWS Cognito
If you've been running Keycloak as your identity provider, you already know it's powerful, flexible, and completely free. But it also comes with operational overhead: you have to host it, patch it, scale it, and babysit its database. At some point, many teams building FastAPI backends ask the same question — what if we let AWS handle authentication instead?
That's where AWS Cognito comes in. It's a fully managed identity service that handles user pools, token issuance, password resets, and social logins without you having to maintain a single server. If your app already lives inside AWS, migrating to Cognito can simplify your infrastructure significantly.
This guide walks through a practical, code-level approach to migrate Keycloak to Cognito inside a FastAPI backend — covering configuration, token validation, and the frontend adjustments your React app will need along the way.
Understanding the Core Differences
Before touching any code, it helps to understand how these two systems differ conceptually, because that difference drives almost every code change you'll make.
Keycloak's Approach
Keycloak issues JWTs signed with its own realm keys. Your FastAPI backend typically validates tokens by fetching the realm's public keys from a well-known JWKS endpoint, then verifying the signature and claims (issuer, audience, expiration) locally.
Cognito's Approach
AWS Cognito works in a conceptually similar way — it also issues JWTs and exposes a JWKS endpoint — but the claim structure, issuer URL format, and token types (ID token vs. Access token) are different. Cognito also separates User Pools (authentication) from Identity Pools (authorization to AWS resources), which Keycloak doesn't distinguish in the same way.
The good news: if your FastAPI backend already validates JWTs using a JWKS-based approach (as most well-structured apps do), the migration is mostly a matter of swapping configuration values and adjusting claim names — not rewriting your entire auth layer.
Step 1: Set Up Your Cognito User Pool
Start by creating a Cognito User Pool in the AWS console (or via Terraform/CDK if you manage infrastructure as code). At minimum, configure:
- App client settings, including allowed OAuth flows and callback URLs
- Password policies that match or exceed what you enforced in Keycloak
- Custom attributes if your Keycloak realm used custom user attributes
- Hosted UI or API-based authentication, depending on how your React frontend handles login
Take note of your User Pool ID, App Client ID, and Region — you'll need these in your FastAPI configuration.
Step 2: Update Your FastAPI Configuration
In a typical FastAPI project, authentication configuration usually lives in a settings module or environment file. Where you previously had something like:
KEYCLOAK_REALM_URLKEYCLOAK_CLIENT_IDKEYCLOAK_JWKS_URL
You'll now introduce Cognito equivalents:
COGNITO_USER_POOL_IDCOGNITO_APP_CLIENT_IDCOGNITO_REGIONCOGNITO_JWKS_URL— typically formatted ashttps://cognito-idp.{region}.amazonaws.com/{user_pool_id}/.well-known/jwks.json
If you followed good practice while building your Keycloak integration — keeping configuration values out of your business logic and centralized in one settings module — this step becomes a simple environment variable swap rather than a full rewrite.
Step 3: Refactor Token Validation Logic
This is where most of the real engineering work happens. Your existing JWT validation dependency probably looks something like this for Keycloak:
def get_current_user(token: str = Depends(oauth2_scheme)):
    jwks = get_keycloak_jwks()
    payload = jwt.decode(token, jwks, audience=KEYCLOAK_CLIENT_ID, issuer=KEYCLOAK_REALM_URL)
    return payload
For Cognito, the structure stays similar, but you need to account for a few key differences:
- Cognito tokens use
token_useas a claim to distinguish between id and access tokens — decide which one your API should validate - The
audclaim is only present on ID tokens; access tokens useclient_idinstead - The issuer format changes to
https://cognito-idp.{region}.amazonaws.com/{user_pool_id}
A refactored dependency typically looks like this:
def get_current_user(token: str = Depends(oauth2_scheme)):
    jwks = get_cognito_jwks()
    payload = jwt.decode(
        token,
        jwks,
        issuer=f"https://cognito-idp.{REGION}.amazonaws.com/{USER_POOL_ID}",
        options={"verify_aud": False}
    )
    if payload.get("client_id") != APP_CLIENT_ID:
        raise HTTPException(status_code=401, detail="Invalid client")
    return payload
This pattern keeps your dependency injection structure — the part FastAPI developers love most — completely intact. You're not changing how authentication plugs into your routes, just how the token gets validated underneath.
Step 4: Handle the User Registration Endpoint
If your app has a custom /auth/register endpoint (as many FastAPI + React apps do), you'll need to redirect that logic to Cognito's SignUp API instead of writing directly to your own user table or calling Keycloak's admin API.
Using boto3, a typical registration handler becomes:
client = boto3.client("cognito-idp", region_name=REGION)
@router.post("/auth/register")
def register(user: UserCreate):
    response = client.sign_up(
        ClientId=APP_CLIENT_ID,
        Username=user.email,
        Password=user.password,
        UserAttributes=[{"Name": "email", "Value": user.email}]
    )
    return {"message": "Registration successful, please confirm your email"}
Notice the shift in mental model: Cognito requires an email confirmation step by default, which Keycloak may not have enforced depending on your realm settings. Make sure your React registration form and success messaging account for this extra confirmation step, so users aren't confused when they can't log in immediately after signing up.
Step 5: Update the Frontend Auth Flow
Your React app likely already has a login form that posts credentials to your backend, stores the returned token in local storage, and uses that token for subsequent authenticated requests. The good news is that this overall pattern — login → token storage → conditional navigation — doesn't need to change structurally when you switch identity providers.
What does change:
- The shape of the token response (Cognito returns
IdToken,AccessToken, andRefreshTokenseparately) - Token refresh logic, since Cognito access tokens typically expire faster than a Keycloak-issued token might
- Error message handling, since Cognito's error codes and messages differ from Keycloak's
If you've built your login page with clean separation between the form UI, the network client, and the token storage logic (a pattern emphasized throughout the React lectures in this course), updating these pieces becomes a matter of adjusting a few functions rather than rewriting your authentication UI from scratch.
Step 6: Test the Full Authentication Loop
Before decommissioning Keycloak, verify the entire loop end-to-end:
- Register a new user through the updated
/auth/registerendpoint - Confirm the account via the email verification flow
- Log in and confirm the token is stored correctly in local storage
- Access a protected route and confirm the FastAPI dependency validates the Cognito token successfully
- Test logout and confirm redirection behaves as expected
Running through this checklist catches most integration issues before they reach production — especially subtle ones like audience mismatches or expired JWKS caching.
Common Pitfalls to Watch For
- Caching JWKS incorrectly — Cognito rotates keys occasionally, so avoid hardcoding fetched keys indefinitely
- Confusing ID tokens with access tokens — decide early which one your backend expects and stay consistent
- Forgetting email verification — Cognito's default flow requires confirmation, unlike some Keycloak configurations
- Not updating CORS and callback URLs — Cognito app clients require exact callback URL matches
Where This Fits Into the Bigger Picture
Authentication is one of those systems that touches almost every layer of a full stack application — from your FastAPI dependency injection setup, to your React login form, to how tokens are stored and refreshed on the client. If you're building toward a production-ready application, understanding both Keycloak-style and Cognito-style JWT validation gives you flexibility to choose the right identity provider for each project you work on.
The Full Stack Python Architect: FastAPI + React + Vibe Coding course walks through this exact authentication architecture step by step — from building the React login and registration pages, to implementing token handling with local storage, to structuring FastAPI routers and dependencies cleanly. If you want a guided, hands-on walkthrough of building (and later adapting) an authentication system like the one described here, it's worth exploring as a companion to this migration guide.
Featured Video
[Video embed placeholder: Watch the full walkthrough of building and adapting authentication flows in FastAPI + React.]
Key Takeaways
- Migrating from Keycloak to Cognito is mostly a configuration and claim-mapping exercise, not a full rewrite, if your JWT validation is already well-structured
- Pay close attention to token types (ID vs. access) and issuer/audience claim differences between the two providers
- Update your registration endpoint to use Cognito's SDK-based sign-up flow, including email confirmation handling
- Keep your React frontend's login, token storage, and navigation logic modular so provider swaps don't require rebuilding the UI
- Always test the full authentication loop — registration, confirmation, login, protected routes, and logout — before decommissioning your old identity provider
Switching identity providers can feel daunting, but with a clear plan and a well-structured FastAPI + React codebase, it's a very manageable engineering task. Take it step by step, test thoroughly, and you'll have a smoother, more scalable authentication system running on AWS Cognito in no time.