Keycloak Tenants vs Realms: For Fun and Profit
Keycloak is an open-source Identity and Access Management (IAM) solution security best practices with attack scenario
Picture Keycloak as a medieval kingdom where realms are the territories, and tenants are the business entities operating within them. Understanding the distinction between realms and tenants is crucial for building scalable, secure identity infrastructure. This article explores the offensive attack surface, defensive mitigation strategies, practical implementations, and real-world deployments that turn this distinction into profit and security.
The stakes? Misconfiguration could leak customer data, compromise application security, and violate compliance regulations. Done right? Your infrastructure becomes a fortress of identity management.
Foundational Concepts
What Makes Keycloak Special?
Keycloak is an open-source Identity and Access Management (IAM) solution that provides:
OpenID Connect (OIDC) and SAML 2.0 support
Multi-protocol authentication and authorization
Scalable architecture for enterprise deployments
Federation capabilities across multiple identity providers
The Kingdom Metaphor
┌─────────────────────────────────────┐
│ KEYCLOAK KINGDOM │
│ ┌──────────────┐ ┌──────────────┐ │
│ │ REALM 1 │ │ REALM 2 │ │
│ │ ┌──────────┐ │ │ ┌──────────┐ │ │
│ │ │ Tenant A │ │ │ │ Tenant C │ │ │
│ │ │ Tenant B │ │ │ │ Tenant D │ │ │
│ │ └──────────┘ │ │ └──────────┘ │ │
│ └──────────────┘ └──────────────┘ │
└─────────────────────────────────────┘
Realms: The Kingdom’s Core
Understanding Realms
A realm in Keycloak is a security domain that manages a complete set of users, applications, roles, and configurations. Think of it as a separate Keycloak instance logically isolated from others.
Key Characteristics:
Isolation Level: Realms are logically isolated but share the same Keycloak instance
User Base: Each realm maintains its own user repository
Applications: Clients (applications) belong to specific realms
Federation: Can federate with external identity providers independently
Audit Logging: Separate audit trails per realm
Realm Structure
Aspect Description Name Unique identifier (e.g., production, staging) Master Realm Administrative realm managing other realms Users Isolated user directories per realm Roles Realm-specific and client-specific roles Tokens Realm-scoped JWT tokens with realm-specific claims Policies Password, session, token, and login policies
Creating a Realm
# Using Keycloak Admin CLI
kcadm.sh create realms \
-s realm=acme-corp \
-s enabled=true \
-s displayName=”ACME Corporation Realm”
Configuration in realm.json:
{
“realm”: “acme-corp”,
“displayName”: “ACME Corporation”,
“enabled”: true,
“bruteForceProtected”: true,
“permanentLockout”: false,
“maxFailureWaitSeconds”: 900,
“minimumQuickLoginWaitSeconds”: 60,
“waitIncrementSeconds”: 60,
“quickLoginCheckMilliSeconds”: 1000,
“maxDeltaTimeSeconds”: 43200,
“failureFactor”: 30,
“accessTokenLifespan”: 300,
“accessTokenLifespanForImplicitFlow”: 900,
“offlineSessionIdleTimeout”: 2592000,
“sslRequired”: “external”
}
Tenants: The Multi-Tenant Revolution
What Are Tenants?
Tenants in Keycloak represent business entities or customer organizations that operate independently within a shared infrastructure. This is achieved through:
Realm-based Tenancy: Each tenant gets a dedicated realm
Namespace-based Tenancy: Shared realm with namespace isolation
Custom Attribute Tenancy: Attribute-driven tenant separation
Multi-Tenancy Architecture Patterns
Pattern Isolation Scalability Cost Complexity Realm per Tenant High Medium High Medium Namespace in Shared Realm Medium High Low High Attribute-Based Medium High Low Very High
Realm-Per-Tenant Model (Recommended for Security)
Each customer organization receives a dedicated realm:
# Onboarding Customer: TechCorp Inc
kcadm.sh create realms \
-s realm=techcorp-inc \
-s enabled=true \
-s displayName=”TechCorp Inc” \
-s accessTokenLifespan=600 \
-s sslRequired=all
Advantages:
✅ Complete isolation of user data
✅ Independent security policies per tenant
✅ Separate audit trails for compliance
✅ Zero data leakage between tenants
Disadvantages:
❌ Higher operational overhead
❌ More resource consumption
❌ Complex scaling
Namespace-Based Tenancy (Shared Realm Model)
All tenants share a single realm but use organizational hierarchies:
# User attributes include tenant namespace
{
“username”: “john.doe@techcorp.com”,
“email”: “john.doe@techcorp.com”,
“attributes”: {
“tenant_id”: “techcorp”,
“organization_namespace”: “techcorp/engineering”,
“department”: “security”
}
}
Advantages:
✅ Lower infrastructure costs
✅ Easier horizontal scaling
✅ Simplified backup/restore
Disadvantages:
❌ Potential for cross-tenant data leaks
❌ Complex access control logic
❌ Harder to audit per tenant
Attack Vectors: The Offensive Playbook
Attack Scenario 1: Realm Escape via Token Manipulation
Threat Model: An attacker attempts to escalate privileges by forging or manipulating JWT tokens to access resources in other realms.
Attack Context: JWT tokens are the cornerstone of modern authentication in Keycloak deployments. However, many applications make a critical security mistake: they validate the cryptographic signature of the token but fail to validate realm-specific claims like iss (issuer), aud (audience), and custom realm claims. This creates an attack vector where adversaries can manipulate token contents while maintaining valid signatures (if weak algorithms like HS256 are used with leaked secrets) or bypass validation entirely in applications that trust token contents without proper verification.
Technical Impact: Successful realm escape attacks enable:
Horizontal Privilege Escalation: Access resources belonging to other tenants at the same privilege level
Vertical Privilege Escalation: Elevate from regular user to admin by targeting privileged realms
Compliance Breach: Unauthorized cross-realm access violates data isolation requirements (GDPR Article 32)
Audit Trail Evasion: Actions performed using manipulated tokens appear legitimate in logs
Real-World Scenario: In 2023, a penetration test revealed that a Fortune 500 company’s multi-tenant SaaS platform accepted tokens from their “sandbox” realm to access “production” realm resources, exposing 100,000+ customer records.
Attack Technique: JWT Header Injection
import jwt
import json
import base64
# Original valid token
original_token = “eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyZWFsbSI6ImFjbWUtY29ycCIsInN1YiI6InVzZXIxIn0.xyz”
# Decode without verification
parts = original_token.split(’.’)
header = json.loads(base64.b64decode(parts[0] + ‘==’))
payload = json.loads(base64.b64decode(parts[1] + ‘==’))
# ATTACK: Modify realm claim
payload[’realm’] = ‘target-realm’
payload[’aud’] = ‘target-application’
# Re-encode (requires secret key if algorithm enforced)
forged_token = jwt.encode(payload, ‘secret’, algorithm=’HS256’)
print(f”[+] Forged Token: {forged_token}”)
print(f”[+] New Realm: {payload[’realm’]}”)
Visual Diagram:
Attack Flow Diagram:
Attack Scenario 2: Cross-Tenant Data Access (Namespace Bypass)
Keep reading with a 7-day free trial
Subscribe to DevSecOps Guides to keep reading this post and get 7 days of free access to the full post archives.





