
Keycloak Organizations: Multi-Tenant Identity Management
An examination of Keycloak Organizations for multi-tenant identity management and B2B scenarios in recent Keycloak versions.
This is Part 14 of the Keycloak Masterclass Series.
In recent Keycloak versions, the architecture for multi-tenancy undergoes a fundamental shift. Historically, administrators achieved isolation by spinning up distinct realms for each client or tenant, creating a rigid infrastructure where a single user account could not easily traverse boundaries. The keycloak-organizations feature introduces a different mechanism: it treats an organization not as a configuration boundary, but as a runtime data object within a single realm. This allows a single Keycloak instance to host thousands of logical tenants, each with its own membership, roles, and identity provider mappings, without the overhead of managing separate database schemas or authentication flows for each.
The core mechanism relies on the separation of the organization entity from the realm entity. In a standard Keycloak setup, roles are attached directly to users or groups within a realm. In the Organizations model, roles are attached to organizations. When a user logs in, the authentication flow does not just resolve a set of roles; it resolves the user's membership in specific organizations and aggregates the roles defined within those contexts. This creates a dynamic scope where a user's permissions are not static but are a function of their current organizational context.
The Mechanism of Scope
Consider the data flow for a B2B collaboration scenario. You have a service provider, "CloudSaaS," running a single Keycloak realm. Two clients, "Acme Corp" and "Beta Inc," need to access specific resources. In the legacy model, you would create two realms, acme-realm and beta-realm. With Organizations, you create one organization object named acme-corp and another named beta-inc.
When "John Doe" from "Beta Inc" attempts to access a resource, the system performs a specific lookup chain. First, the authentication provider validates John's credentials. Second, the system queries the membership table to find which organization John belongs to. If John is a member of beta-inc, the system fetches the roles associated with beta-inc (e.g., beta-user, beta-admin). These roles are then injected into the JWT access token under resource_access for the specific client or as custom claims, unless explicitly mapped to realm roles. The critical distinction is that the token payload changes based on the organization context, not the realm configuration.
To implement this, you interact with the Keycloak Admin REST API. You do not create realms; you create organizations.
# Create the Acme Corp organization
curl -X POST "http://localhost:8080/admin/realms/master/organizations" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $ADMIN_TOKEN" \
-d '{
"name": "Acme Corp",
"displayName": "Acme Corporation",
"description": "Primary client organization for Acme"
}'
# Invite a user to the organization
curl -X POST "http://localhost:8080/admin/realms/master/organizations/acme-corp/memberships" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $ADMIN_TOKEN" \
-d '{
"userId": "john-doe-uuid",
"roles": ["acme-user", "acme-admin"]
}'Notice that the roles in the membership payload are local to the organization. This is where the mechanism diverges from group-based role assignment. A role assigned to a user globally in the realm applies to everyone. A role assigned to an organization applies only to members of that organization. This allows "Acme Corp" to have an admin role that has full access to their data, while "Beta Inc" has a different admin role with restricted access to their own data, all within the same realm.
B2B Workflow Construction
For B2B scenarios involving identity federation, the isolation mechanism becomes even more critical. You often need to allow users from external identity providers (IdPs) to join your organization without them having accounts in your internal directory. Keycloak Organizations handles this by allowing you to configure Identity Provider Mappers or Organization User Mappers at the organization level.
When a user authenticates via an external IdP (e.g., Microsoft Entra ID), the incoming token contains claims like email or group. Keycloak uses these claims to determine which organization the user should join, but this requires explicit configuration of these mappers to match the incoming group claim to an existing organization name. Once the user is mapped to an organization, the system automatically assigns the predefined roles for that organization.
This mechanism ensures tenant isolation without requiring separate realms. The sub (subject) claim in the JWT remains consistent for the user across organizations, but the roles and resource_access claims change based on the active organization context. This is vital for B2B applications where a single user might be a guest in multiple partner organizations.
Identity Federation and Isolation
The implementation of this pattern requires a shift in how you view your identity data. Instead of thinking in terms of "users in realms," you think in terms of "users in organizations." The organization entity becomes the primary unit of isolation. This aligns better with modern B2B business models where customers are organizations, not just individual users. By leveraging the mechanism of organization-scoped roles and memberships, you can build identity systems that scale with your business logic rather than your infrastructure constraints.
In practice, the most common pattern for B2B identity solutions in recent Keycloak versions involves a hybrid approach. You use a single realm for the core identity management, leveraging Organizations for logical grouping and role inheritance. You then use the organization scope in your resource server configuration to restrict API access. For example, an API endpoint might require the acme-user role. The resource server checks the token, sees the user is a member of acme-corp, verifies the acme-user role exists within that organization's scope, and grants access. This creates a robust, scalable, and auditable B2B identity layer.
Operational Tradeoffs
However, this architecture introduces specific tradeoffs. In a realm-per-tenant model, if "Acme Corp" misbehaves or consumes excessive resources, it does not affect "Beta Inc" because they are in completely separate database schemas and authentication flows. In the Organizations model, all tenants share the same database and the same authentication infrastructure. While modern versions have improved performance, the "noisy neighbor" problem still exists at the infrastructure level. If the database locks up due to a query from one organization, it impacts all others.
Furthermore, managing the lifecycle of organizations requires careful attention to the membership state. Unlike a realm, which is a persistent configuration object, an organization is a dynamic container. If you delete an organization, you must explicitly handle the cleanup of all memberships and the revocation of associated tokens. This adds operational complexity to the deployment pipeline. You cannot simply delete a realm; you must iterate through memberships, revoke tokens, and then delete the organization object.
The decision to use Keycloak Organizations over realm-per-tenant depends entirely on your scale and isolation requirements. If you need strict data isolation at the database level and your tenants are large enterprises with dedicated infrastructure, realm-per-tenant remains the safer choice. If you are building a SaaS platform with hundreds of small-to-medium tenants where rapid onboarding and shared infrastructure are priorities, the Organizations model provides the necessary granularity without the administrative overhead.
Conclusion
Ultimately, Keycloak Organizations represents a maturation of the platform's multi-tenancy capabilities. It moves the complexity from the infrastructure layer (managing realms) to the application layer (managing organizations and memberships). This shift allows developers to focus on business logic and tenant relationships rather than the mechanics of identity provisioning. For advanced users, this offers a powerful, flexible tool for building complex B2B identity solutions, provided the operational risks of shared infrastructure are understood and mitigated.
Common Pitfalls
When implementing Keycloak Organizations, several pitfalls frequently arise that can compromise security or stability:
- Shared Infrastructure Risks: Assuming complete isolation between tenants. Since all organizations share the same database and authentication infrastructure, a poorly optimized query or a denial-of-service attempt by one tenant can degrade performance for all others. Proper database indexing and connection pooling are critical.
- Membership Cleanup Complexity: Failing to clean up memberships during organization deletion. Unlike deleting a realm, which cascades deletes, deleting an organization requires a manual or scripted process to revoke tokens, remove memberships, and clean up associated client scopes. Neglecting this leaves orphaned data and potential security vulnerabilities.
- Role Scope Confusion: Misunderstanding the difference between realm-level and organization-level roles. Assigning a role to an organization does not automatically make it a realm role. Developers often expect
realm_accessto contain organization roles, leading to authorization failures in resource servers that expect specific claim structures.
Practical Takeaways
To successfully implement multi-tenancy with Keycloak Organizations, adopt these mental models:
- Organizations as Contexts: View organizations not as users, but as dynamic contexts that wrap around users. A user's permissions are a product of
User + Organization. - Explicit Mapping is Mandatory: Do not rely on default behaviors for identity federation. Always explicitly configure Identity Provider Mappers to handle the translation of external claims into internal organization memberships.
- Resource-Centric Authorization: Design your resource server policies to check for organization membership and roles within
resource_accessrather than relying solely on realm-level roles. This ensures the correct scope is enforced at the API level.
FAQ
Q: Can a user belong to multiple organizations simultaneously? A: Yes, a single user can be a member of multiple organizations. However, their effective roles and permissions are determined by the specific organization context they are accessing at that moment.
Q: Does deleting an organization automatically revoke active sessions? A: No. Deleting an organization removes the configuration and memberships but does not immediately invalidate active JWTs or sessions. You must implement a token revocation strategy or rely on short token lifetimes to mitigate this risk.
Q: How does role inheritance work in Keycloak Organizations? A: Roles can be inherited if an organization is configured to inherit from a parent organization or if roles are defined at the realm level and assigned to the organization. However, by default, roles defined within an organization are scoped strictly to that organization unless explicitly mapped otherwise.
Call to Action
Before deploying a multi-tenant architecture, audit your current rotation policy and review the official Keycloak Organizations API documentation to ensure your implementation aligns with the latest security standards.
Related posts
Implementing WebAuthn in Keycloak: Passkey Authentication Setup
A walkthrough for configuring WebAuthn and passkeys within Keycloak to enable passwordless authentication using FIDO2 standards.
Keycloak Client Scopes and Protocol Mappers Explained
A detailed look at Keycloak client scopes and protocol mappers for token customization and claim management.
Keycloak and Spring Boot Integration: Advanced Patterns
Explore advanced Keycloak and Spring Boot integration patterns including multi-tenant setups and reactive security.