In today’s digital landscape, secure authentication and authorization are critical for any application, especially those serving multiple clients or tenants. Keycloak, an open-source identity and access management (IAM) solution, stands out for its flexibility in handling complex scenarios like multi-tenant environments. This blog post draws from a real-world implementation where Keycloak was integrated to support dual authentication flows—one using a client’s local database and another leveraging Keycloak’s capabilities. We’ll explore the motivations, technical implementation, multi-tenancy strategies, and best practices, while highlighting how solutions like those from 47 Billion can streamline such deployments.
Keycloak excels in providing standards-compliant support for protocols like OpenID Connect (OIDC) and OAuth 2.0/2.1, making it ideal for modern applications requiring single sign-on (SSO), role-based access control (RBAC), and secure token management. Whether you’re dealing with multi-tenant SSO or customizing login flows, Keycloak’s architecture ensures scalability and security.

ImageSource: https://developers.redhat.com/blog/2019/12/11/keycloak-core-concepts-of-open-source-identity-and-access-management
Why Choose Keycloak for Authentication and Authorization?
The project in question arose from a client’s need for a hybrid authentication system. They had an existing local logic for user authentication and authorization but wanted the option to switch to Keycloak for enhanced security and scalability. This dual-flow requirement led to a flag-based system: if the flag is true, requests route through Keycloak; if false, they use the local setup.
Keycloak was selected for its standalone nature, which simplifies deployment compared to microservices-based alternatives. It acts as an identity provider (IdP), brokering between applications and external logins (e.g., Google or Microsoft). In multi-tenant scenarios, Keycloak’s realms and clients enable isolated environments, preventing data leakage between tenants.
According to Keycloak’s official documentation, realms serve as isolated security domains, each managing its own users, clients, and configurations. This isolation is key for multi-tenancy, where each tenant (e.g., different organizations) can have customized authentication policies without interfering with others.
Core Security Protocols: OIDC, OAuth 2.0, and SAML Explained
To understand the implementation, let’s delve into the foundational protocols.
OpenID Connect (OIDC) is an authentication layer built on OAuth 2.0, allowing clients to verify user identities and obtain basic profile information. It uses ID tokens (JWTs) to convey user details securely.
OAuth 2.0 focuses on authorization, defining how clients obtain access tokens to access protected resources. It supports grant types like Authorization Code Flow (for web apps), Client Credentials (for machine-to-machine communication) and password grant (depricated in OAuth 2.1). In practice, OIDC and OAuth 2.0 are often used together: OIDC handles “who you are,” while OAuth manages “what you can do.”
SAML (Security Assertion Markup Language), an older XML-based standard, is still used in enterprise settings for SSO but has largely been supplanted by OIDC for its simplicity and JSON-based tokens.
In the flow, users are redirected to the Keycloak login page, authenticate, and receive an access token containing roles, scopes, and claims. The backend validates this token using Keycloak’s public key, which can be cached for efficiency. Refresh tokens allow seamless session renewal without re-authentication.

ImageSource: https://darutk.medium.com/diagrams-and-movies-of-all-the-oauth-2-0-flows-194f3c3ade85
For added depth, OAuth 2.0 includes scopes to limit access—e.g., a “read:user” scope permits GET requests but not modifications. This granular control is essential for RBAC in multi-tenant setups.
Implementing the Dual-Flow System with Middleware
The core of the implementation was a custom middleware that intercepts requests based on the flag. When enabled, it validates the access token’s signature and checks scopes against the requested endpoint.
For example, endpoints like /users (GET for listing, POST for creation) were grouped into resources. Scopes such as “read:users” bundled all GET operations, while “write:users” covered POST and PUT. If the token lacks the required scope, the middleware returns a 401 Unauthorized response and revokes the tokens.
Admin management was automated via Keycloak’s REST APIs, avoiding manual UI interventions. Scripts handled user creation, role assignment, and permission syncing between Keycloak and the local system. This end-to-end automation ensured consistency, especially in multi-tenant environments where admins manage tenant-specific resources.
Common pitfalls included “account not fully set up” errors, often due to missing required fields in user profiles. Debugging involved checking realm settings for mandatory attributes like email verification.
Security best practices were paramount: access tokens expired in 5-6 minutes, with longer-lived refresh tokens (hours). Tokens were stored securely on the frontend, and all communications used HTTPS.
Frontend Integration: Conditional Rendering Based on Permissions
While the backend ensures data integrity, the frontend must interpret these security constraints to provide a seamless user experience.
On the client side, conditional rendering enhanced user experience. After login, an API decoded the JWT to extract roles and scopes, mapping them to UI elements. For instance, a user with only “read:users” saw the users page but without create/update buttons. Sidebar menus dynamically showed only accessible sections, preventing unauthorized attempts and improving professionalism over raw 401 errors.
This approach aligns with Keycloak’s client roles, where permissions are scoped to specific applications, ensuring fine-grained control in multi-tenant apps.
Handling Multi-Tenancy: Realms, Clients, and Subdomain Redirection
Multi-tenancy was a highlight, using Keycloak’s realms for isolation. Realms are top-level containers; within them, clients represent applications sharing users but with distinct authorizations.
For separate tenants without shared users, create dedicated realms (e.g., realm-A, realm-B). For related services, use one realm with multiple clients, sharing resources like users but customizing roles per client—a user might be an admin in one client but a viewer in another.
Subdomain mapping addressed redirection: for sites like service-a.exmaple.ai, configure client-specific redirect URIs in Keycloak. Upon authentication, OIDC redirects to the tenant’s frontend (e.g., https://johndoe.example.ai/dashboard). At the code level, the login request includes the client ID, ensuring Keycloak authenticates against the correct client and redirects accordingly.
Keycloak’s user federation further enhances this by linking to external directories (e.g., LDAP), allowing user management in your database while Keycloak handles auth. Sync modes like import or read-only keep data consistent.

Image Source: https://www.youtube.com/watch?v=LxAos2PGdus
The newer “Organizations” feature in Keycloak allows multi-tenancy within a single realm, grouping users and IdPs for hierarchical management—ideal for SaaS platforms.
Keycloak vs. Ory: Choosing the Right IAM Solution
While Keycloak proved effective, comparisons with Ory (an open-source IAM stack) are common. Keycloak is a monolithic, standalone service with a user-friendly Admin Console for managing everything centrally—realms, clients, roles, and more. It’s fully free, feature-rich, and easier for beginners, with built-in support for multi-tenancy via realms.
Ory, conversely, is microservices-based (e.g., Kratos for identities, Hydra for OAuth, Oathkeeper for proxies, Keto for policies). This modularity offers flexibility—replace components as needed—and lower memory usage, but it increases complexity in setup and documentation. Ory excels in Kubernetes environments and follows strict industry standards, but lacks Keycloak’s intuitive UI, requiring more configuration files.
In the project, Keycloak’s ease won out for the standalone deployment, though Ory’s flexibility was noted for microservices-heavy architectures. Market share data shows Keycloak at around 1.7% in IAM tools, dwarfing Ory’s 0.01%, reflecting its maturity.
Navigating the choice between Keycloak and Ory ultimately comes down to your team’s specific infrastructure needs and long-term scaling goals. While Keycloak offers a ‘batteries-included’ experience that accelerates time-to-market, Ory provides the modularity required for highly custom, cloud-native environments. Regardless of the tool, the priority should always be on creating an identity layer that is both invisible to the user and impenetrable to bad actors. Achieving this balance requires a disciplined approach to automation, rigorous security audits, and a deep understanding of how multi-tenancy affects token logic.
Best Practices and Lessons Learned
- Token Management: Use short-lived access tokens and cache public keys for validation.
- Automation: Leverage Keycloak APIs for user and permission management to avoid manual errors.
- Debugging: Check required fields and realm settings for common setup issues.
- Scalability: For high-traffic multi-tenant apps, consider clustering Keycloak instances.
- Security: Enforce MFA, monitor token revocations, and use fine-grained scopes.
This implementation not only met the client’s unique needs but also reinforced Keycloak’s strengths in handling complex auth scenarios. If you’re exploring Keycloak for your multi-tenant authentication and authorization needs, start with the official docs and consider expert consultation for robust security.