Keycloak Multi-Tenancy with Organizations: The Complete Guide for SaaS
How to implement multi-tenancy in Keycloak using the Organizations feature. Covers architecture, tenant isolation, per-tenant branding, delegated admin, and common pitfalls.
KeycloakPro Team
KeycloakPro Team
Why Multi-Tenancy Matters for SaaS
Every SaaS application eventually needs to answer the same question: how do you serve hundreds or thousands of customers from a single platform while keeping their data, users, and configurations completely isolated?
Identity management sits at the center of this problem. Each tenant may need its own login experience, identity providers, user roles, and branding. Get this wrong and you face data leaks between tenants, an operational nightmare at scale, or a system so rigid it cannot onboard new customers without engineering effort.
Keycloak has been the go-to open-source IAM solution for years, but its multi-tenancy story was historically painful. That changed with Keycloak Organizations, introduced as a preview in Keycloak 24 and stabilized in Keycloak 26.
The Old Way: Realm-Per-Tenant (and Why It Fails)
The traditional approach to multi-tenancy in Keycloak was to create a separate realm for each tenant. On paper, this provides strong isolation: each realm has its own users, clients, roles, and IdP configurations.
In practice, it breaks down fast.
The Realm-Per-Tenant Problem
| Concern | Impact at Scale |
|---|---|
| Database load | Each realm creates hundreds of database rows for default clients, roles, scopes. At 500 tenants, your DB has millions of configuration rows. |
| Memory consumption | Keycloak caches realm metadata in memory. Hundreds of realms can exhaust heap space. |
| Operational burden | Updating a client configuration across 500 realms requires scripting against every single realm. |
| Startup time | Keycloak loads realm metadata at boot. More realms means slower restarts. |
| No shared user pool | A user who belongs to multiple tenants needs separate accounts in each realm, with separate credentials. |
| Monitoring complexity | Metrics, logs, and alerts must be configured per-realm or carefully aggregated. |
The rule of thumb: realm-per-tenant works for 5-20 tenants. Beyond that, you are managing an IAM platform, not building your product.
Some teams tried workarounds: groups-as-tenants, client-scoped roles, or custom SPIs. These were fragile, undocumented, and broke across Keycloak upgrades.
The New Way: Keycloak Organizations
Starting in Keycloak 26, Organizations is a first-class, stable feature that provides multi-tenancy within a single realm. It was designed specifically for the SaaS use case.
How Organizations Work
An Organization in Keycloak represents a tenant. Within a single realm, you can create thousands of organizations, each with:
- Members -- users who belong to that organization
- Identity Providers -- per-tenant SSO connections (e.g., Tenant A uses Okta, Tenant B uses Azure AD)
- Domains -- verified email domains that auto-route users to the correct organization
- Roles and permissions -- scoped to the organization context
The key architectural shift: users exist in the realm, organizations are a membership layer on top. A single user can belong to multiple organizations, which is exactly what B2B SaaS products need.
Architecture Overview
Single Realm: "my-saas"
|
|-- Organization: "Acme Corp"
| |-- Members: alice@acme.com, bob@acme.com
| |-- IdP: Acme's Azure AD (SAML)
| |-- Domain: acme.com
|
|-- Organization: "Globex Inc"
| |-- Members: carol@globex.com, dave@globex.com
| |-- IdP: Globex's Okta (OIDC)
| |-- Domain: globex.com
|
|-- Organization: "Initech"
|-- Members: peter@initech.com
|-- IdP: None (uses realm default login)
|-- Domain: initech.com
All organizations share the same realm clients, authentication flows, and base configuration. Tenant-specific customization happens at the organization level.
Implementation Walkthrough
Prerequisites
- Keycloak 26 or later
- Organizations feature enabled (it is enabled by default in KC 26+)
- Admin REST API access
Step 1: Enable Organizations on the Realm
Organizations must be enabled at the realm level. If you are using Keycloak 26+, this is already the default. To verify or enable it via the Admin API:
# Get current realm settings
curl -s -X GET \
"http://localhost:8080/admin/realms/my-saas" \
-H "Authorization: Bearer $ACCESS_TOKEN" | jq '.organizationsEnabled'
# Enable organizations if not already enabled
curl -s -X PUT \
"http://localhost:8080/admin/realms/my-saas" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"organizationsEnabled": true}'
Step 2: Create an Organization
curl -s -X POST \
"http://localhost:8080/admin/realms/my-saas/organizations" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "acme-corp",
"alias": "acme-corp",
"enabled": true,
"domains": [
{
"name": "acme.com",
"verified": true
}
],
"attributes": {
"displayName": ["Acme Corporation"],
"plan": ["enterprise"],
"maxUsers": ["500"]
}
}'
The response includes the organization ID, which you will need for subsequent operations.
Step 3: Add Members to the Organization
You can add existing realm users as organization members:
# First, find the user ID
USER_ID=$(curl -s -X GET \
"http://localhost:8080/admin/realms/my-saas/users?email=alice@acme.com" \
-H "Authorization: Bearer $ACCESS_TOKEN" | jq -r '.[0].id')
# Add user as an organization member
curl -s -X POST \
"http://localhost:8080/admin/realms/my-saas/organizations/$ORG_ID/members" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d "{\"id\": \"$USER_ID\"}"
Step 4: Configure a Per-Tenant Identity Provider
This is where Organizations truly shine. You can link an IdP to a specific organization so that only members of that organization use it:
# Create an IdP for the organization
curl -s -X POST \
"http://localhost:8080/admin/realms/my-saas/identity-provider/instances" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"alias": "acme-azure-ad",
"providerId": "oidc",
"enabled": true,
"config": {
"clientId": "acme-client-id",
"clientSecret": "acme-client-secret",
"authorizationUrl": "https://login.microsoftonline.com/acme-tenant-id/oauth2/v2.0/authorize",
"tokenUrl": "https://login.microsoftonline.com/acme-tenant-id/oauth2/v2.0/token",
"defaultScope": "openid profile email"
}
}'
# Link the IdP to the organization
curl -s -X POST \
"http://localhost:8080/admin/realms/my-saas/organizations/$ORG_ID/identity-providers" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"alias": "acme-azure-ad"}'
When a user with an @acme.com email address logs in, Keycloak automatically routes them to the Acme Azure AD identity provider. No custom login page logic required.
Per-Tenant Branding and Themes
Organizations support per-tenant branding through Keycloak's theming system. You can customize the login page for each organization using theme resources or by leveraging organization attributes in a custom theme.
Approach 1: Organization Attributes in Themes
Store branding data as organization attributes:
{
"attributes": {
"brandColor": ["#1a73e8"],
"logoUrl": ["https://cdn.acme.com/logo.png"],
"companyName": ["Acme Corporation"]
}
}
In your custom FreeMarker theme, access these attributes to render tenant-specific login pages. The organization context is available in the login theme when the user is routed through an organization-linked IdP or domain.
Approach 2: Theme Selector SPI
For more advanced scenarios, implement a custom ThemeSelectorProvider SPI that selects a different theme based on the organization context. This gives you full control over CSS, HTML templates, and assets per tenant.
Delegated Admin Model
One of the strongest features of Organizations is delegated administration. You do not need to give every tenant admin access to the Keycloak Admin Console.
Organization Roles
Keycloak Organizations supports built-in organization roles:
| Role | Capabilities |
|---|---|
| admin | Manage members, invite users, manage organization settings |
| member | Standard membership, no admin capabilities |
Setting Up Delegated Admin
# Assign a user as an organization admin
curl -s -X PUT \
"http://localhost:8080/admin/realms/my-saas/organizations/$ORG_ID/members/$USER_ID/organization-roles/admin" \
-H "Authorization: Bearer $ACCESS_TOKEN"
Organization admins can manage their own organization through the Keycloak Account Console or through a custom admin portal that calls the Organizations REST API. They cannot see or affect other organizations.
For a custom admin portal, your application calls the Admin REST API with a token scoped to the organization, allowing tenant admins to:
- Invite new members via email
- Remove members who have left
- View and manage linked IdPs
- Update organization attributes (branding, settings)
Token Claims with Organization Context
Tokens issued by Keycloak can include organization membership information, which your application uses for authorization decisions.
Organization Scope
Request the organization scope during authentication to include org claims in the token:
GET /realms/my-saas/protocol/openid-connect/auth?
client_id=my-app&
scope=openid organization&
response_type=code&
redirect_uri=https://app.example.com/callback
The resulting access token includes organization claims:
{
"sub": "user-uuid",
"email": "alice@acme.com",
"organization": {
"acme-corp": {
"id": "org-uuid",
"roles": ["admin"]
}
},
"iss": "http://localhost:8080/realms/my-saas",
"aud": "my-app"
}
Your application can then extract the organization claim to enforce tenant-scoped access control. No custom protocol mappers or SPIs needed.
Multi-Organization Users
If a user belongs to multiple organizations, the token includes all memberships. Your application should prompt the user to select which organization context they want to operate in, then filter accordingly.
Common Pitfalls and How to Avoid Them
1. Not Verifying Domains
Problem: Without domain verification, any user can claim an email address and potentially land in the wrong organization.
Fix: Always set "verified": true only after confirming domain ownership through DNS TXT records or email verification. Use Keycloak's domain verification flow.
2. Forgetting the Organization Scope
Problem: Tokens do not include organization claims by default. Your app receives tokens with no tenant context.
Fix: Always request the organization scope in your OIDC client configuration. Add it to the default scopes for your client if every request needs org context.
3. Over-Permissive Delegated Admin
Problem: Organization admins can modify configurations that affect security (e.g., disabling MFA for their org).
Fix: Use fine-grained admin permissions to restrict what organization admins can change. Lock down security-critical settings at the realm level.
4. Not Planning for User Migration
Problem: Moving from realm-per-tenant to organizations requires migrating users and their IdP links.
Fix: Plan the migration in phases. Export users from each realm, import them into the shared realm, then create organization memberships. Test with a pilot tenant first.
5. Ignoring IdP Alias Collisions
Problem: Each IdP alias must be unique within the realm. If two tenants both call their IdP "azure-ad", the second creation fails.
Fix: Namespace IdP aliases with the organization name: acme-azure-ad, globex-azure-ad.
Performance Considerations at Scale
Organizations are designed for scale, but there are important tuning considerations as you grow.
| Scale | Consideration | Recommendation |
|---|---|---|
| 100+ organizations | Database query performance for membership lookups | Add indexes on organization membership tables. Monitor query times. |
| 1,000+ organizations | IdP metadata caching | Enable IdP metadata caching to avoid repeated fetches from upstream providers. |
| 10,000+ members per org | Member listing pagination | Always paginate member queries. Never fetch all members at once. |
| High concurrency | Token generation with org claims | Ensure Keycloak's infinispan cache is properly sized for org metadata. |
| Multi-region | Organization data replication | Use Keycloak's cross-datacenter replication with external Infinispan for org data consistency. |
Database Tuning
The organizations feature stores membership data in dedicated tables. At scale, ensure you have proper indexes:
-- Verify these indexes exist (Keycloak creates them by default)
-- If performance degrades, check execution plans for:
SELECT * FROM org_membership WHERE user_id = ?;
SELECT * FROM org_membership WHERE org_id = ?;
SELECT * FROM organization WHERE realm_id = ? AND name = ?;
Horizontal Scaling
Unlike the realm-per-tenant approach, Organizations work well with Keycloak clustering. All nodes in the cluster share the same realm, and organization metadata is cached in the distributed Infinispan cache. Adding more Keycloak nodes linearly improves throughput.
When to Choose Organizations vs. Realms
Not every deployment needs Organizations. Here is a decision framework:
| Scenario | Recommendation |
|---|---|
| < 10 tenants with completely separate user pools | Realm-per-tenant may still work |
| 10-100 tenants, shared user model, B2B SaaS | Organizations (ideal fit) |
| 100+ tenants, per-tenant IdPs, delegated admin | Organizations (only viable option) |
| Tenants that need entirely different auth flows | Separate realms or hybrid approach |
| Users who belong to multiple tenants | Organizations (designed for this) |
Getting Started
Keycloak Organizations eliminates the biggest pain point of building multi-tenant SaaS on open-source IAM. A single realm with organization-scoped isolation gives you the operational simplicity of a shared deployment with the tenant separation your customers demand.
The key steps to get started:
- Upgrade to Keycloak 26+ if you have not already
- Enable Organizations on your realm
- Create organizations for each tenant with verified domains
- Link IdPs per organization for enterprise SSO
- Request the organization scope in your OIDC clients
- Build your admin portal using the Organizations REST API
If you are planning a multi-tenant Keycloak deployment and want expert guidance on architecture, migration from realm-per-tenant, or production-ready configuration, KeycloakPro offers multi-tenancy architecture consulting and managed Keycloak services. We have helped SaaS teams scale from 10 to 10,000+ tenants without the operational headaches. Get in touch to discuss your multi-tenancy strategy.
Need Help With Keycloak?
Our team specializes in production-grade Keycloak deployments. Get a free 30-minute strategy consultation.
Book a Free Strategy Call