Why Teams Move From Keycloak to AWS Cognito
If you've built a Flask application with Keycloak handling your authentication, you already know the drill: realms, clients, tokens, and a self-hosted identity server that you're responsible for patching, scaling, and securing. At some point, many teams start asking a different question—do we really need to manage our own identity server?
That's usually when AWS Cognito enters the conversation. As a fully managed identity provider, Cognito removes the operational overhead of running Keycloak yourself, integrates tightly with the rest of the AWS ecosystem, and scales automatically with your user base. For Flask developers who are already deploying on AWS, a Keycloak to Cognito migration can simplify infrastructure significantly.
But migration is never just a matter of swapping one login button for another. Token structures differ, user pools work differently than realms, and your Flask backend's validation logic needs to be rewritten. This guide walks through the practical steps of a Flask authentication migration—what you need to change, what you can keep, and how to avoid breaking your app in the process.
Understanding the Core Differences
Keycloak's Architecture
Keycloak is a self-hosted, open-source identity and access management solution. In a typical Flask setup, you'd configure a realm, register a client, and use Keycloak's OpenID Connect endpoints to issue JSON Web Tokens (JWTs). Your Flask backend would then validate these tokens using Keycloak's public keys, typically fetched from a JWKS (JSON Web Key Set) endpoint.
Cognito's Architecture
AWS Cognito organizes authentication around User Pools (which manage user directories and authentication) and Identity Pools (which grant temporary AWS credentials, if needed). For most Flask APIs, you'll primarily be working with a User Pool, which—much like Keycloak—issues JWTs and exposes a JWKS endpoint for token verification.
The good news: because both systems are built on OAuth 2.0 and OpenID Connect standards, the shape of your migration work is familiar. You're not reinventing authentication from scratch—you're re-pointing your Flask app at a new token issuer and adjusting for provider-specific quirks.
What Changes When You Switch Identity Providers
1. Token Issuer and Audience Claims
Every JWT includes an iss (issuer) and aud (audience) claim. When you move from Keycloak to Cognito, these values change completely. Your Flask token validation logic must be updated to expect Cognito's issuer URL, which follows this pattern:
https://cognito-idp.{region}.amazonaws.com/{userPoolId}
Any hardcoded references to your old Keycloak realm URL need to be replaced throughout your codebase—including in environment variables, configuration files, and any middleware that validates incoming requests.
2. JWKS Endpoint and Key Rotation
Keycloak and Cognito both expose public keys via a JWKS endpoint, but the URLs and key rotation behavior differ. Cognito's JWKS endpoint is:
https://cognito-idp.{region}.amazonaws.com/{userPoolId}/.well-known/jwks.json
If your Flask app uses a library like PyJWT combined with a JWKS client, you'll largely reuse the same validation pattern—just point it at Cognito's endpoint instead of Keycloak's.
3. Token Structure and Claims
This is where migrations often trip people up. Cognito tokens include claims that Keycloak doesn't, and vice versa. For example:
- Cognito issues separate ID tokens and access tokens, each with different claims and use cases.
- Role and group information is stored differently—Cognito uses
cognito:groups, while Keycloak typically nests roles underrealm_access.roles. - Custom attributes in Cognito must be prefixed with
custom:, which is a departure from Keycloak's more flexible custom claim mapping.
Any Flask decorator or middleware that extracts roles or permissions from the token payload will need to be rewritten to match Cognito's claim structure.
4. User Management Flows
Keycloak's admin console and Cognito's User Pool console look and behave differently. If your Flask backend calls out to Keycloak's admin API for tasks like creating users, resetting passwords, or managing groups, you'll need to replace those calls with equivalent AWS SDK (boto3) calls against Cognito's API. The logic stays conceptually similar—create user, assign group, force password reset—but the API calls and required permissions are entirely different.
What Stays the Same
It's easy to focus on what's changing and forget that a lot of your architecture remains stable. This is good news for anyone worried about a full authentication rewrite.
- Your token validation pattern: If you built your Flask app around standard JWT validation (verify signature, check expiration, check audience), that overall pattern doesn't change—only the configuration values do.
- Your route protection logic: Decorators or middleware that check for a valid token before allowing access to protected routes can remain structurally the same.
- Your frontend token storage strategy: Whether you're storing tokens in local storage, cookies, or memory, that architectural decision on the React side doesn't need to change just because the issuer changed.
- Your overall authentication flow: Login, token retrieval, protected API calls, logout—the user-facing flow remains conceptually identical, even if the underlying provider is different.
A Practical Migration Checklist
Rather than attempting a big-bang cutover, plan your migration in stages:
Step 1: Set Up Your Cognito User Pool
Create a new User Pool in AWS Cognito and configure it to match your existing Keycloak realm as closely as possible—same password policies, similar attribute schemas, and equivalent app client settings.
Step 2: Update Your Flask Token Validation
Replace your Keycloak JWKS client and issuer configuration with Cognito's equivalents. Test this thoroughly using tokens generated directly from the Cognito console before touching your frontend.
Step 3: Migrate or Re-Register Users
Decide whether you'll bulk-import existing users into Cognito (using AWS's user migration Lambda trigger) or require users to re-register. For many teams, a migration Lambda that authenticates against Keycloak on first login and silently creates the Cognito user is the smoothest option—users never notice the switch.
Step 4: Update Role and Permission Mapping
Rewrite any backend logic that reads roles or groups from the token to match Cognito's claim structure. This is a good opportunity to centralize this logic into a single utility function rather than scattering claim-parsing code throughout your app.
Step 5: Update the Frontend Auth Flow
Your React login page, token handling, and redirect logic will need to point to Cognito's hosted UI or SDK instead of Keycloak's login endpoint. If you built your frontend with clean separation between the auth provider and the rest of your app, this should be a contained change.
Step 6: Run Both Providers in Parallel
Where possible, keep Keycloak running alongside Cognito during a transition window. This lets you roll back quickly if something unexpected surfaces in production, and gives users time to migrate gracefully.
Common Pitfalls to Avoid
- Forgetting token expiration differences: Cognito's default token lifetimes differ from Keycloak's. Review and explicitly configure these values rather than assuming defaults match.
- Ignoring refresh token behavior: Cognito handles refresh tokens differently, and your Flask backend or React frontend may need updated logic to handle silent token renewal.
- Skipping the JWKS caching strategy: Just like with Keycloak, you should cache Cognito's public keys rather than fetching them on every request, to avoid unnecessary latency.
- Underestimating claim mapping work: This is consistently the most time-consuming part of any identity provider migration. Budget extra time for testing role-based access control after the switch.
Why This Matters for Full Stack Architecture
Authentication migrations like this one are a great example of why strong architectural thinking matters so much in full stack development. A Flask backend that's tightly coupled to Keycloak-specific implementation details will be painful to migrate. A backend built with clean abstractions around token validation, role extraction, and identity provider configuration will make this kind of transition dramatically easier.
This is exactly the kind of real-world scenario covered in Full Stack Python Architect: Flask + React + Vibe Coding. The course goes beyond just wiring up a login form—it teaches you to build authentication systems with the architectural flexibility to adapt as your infrastructure needs evolve, whether that means switching identity providers, scaling your API, or deploying to production environments. You'll work through secure token handling, local storage strategies, validation, and redirection flows in React, paired with backend design patterns in Flask that keep your authentication logic clean and swappable.
Featured Video
[Video embed placeholder: Watch a full walkthrough of migrating Flask authentication from Keycloak to AWS Cognito, including live token validation testing and role mapping.]
Key Takeaways
- Migrating from Keycloak to Cognito involves updating your issuer URL, JWKS endpoint, and claim-parsing logic—but the overall JWT validation pattern remains the same.
- Cognito's token structure (ID tokens vs. access tokens,
cognito:groups, custom attribute prefixes) requires careful mapping compared to Keycloak's realm-based claims. - A staged migration—new user pool, updated backend validation, user migration strategy, frontend updates, and parallel running—reduces risk significantly.
- Clean architectural separation between your Flask app and your identity provider makes any future switch identity provider scenario far less painful.
Whether you're planning an AWS Cognito migration for cost, scalability, or ecosystem reasons, the underlying principles of good authentication architecture stay constant. Building that architecture correctly from the start—something you'll practice hands-on in the full course—is what makes migrations like this one a manageable engineering task rather than a stressful rewrite.