Skip to main content
AIVO Logo
Security & IAM

Why and How to Implement Keycloak to Secure a Multi-Tenant SaaS Architecture?

Nicolas BAUD

Nicolas BAUD

Senior Software Architect & Eco-design Expert

Published on
Reading time 6 MIN
Why and How to Implement Keycloak to Secure a Multi-Tenant SaaS Architecture?

Introduction: The Identity Management Trap in SaaS

When launching a B2B SaaS, authentication is often relegated to the background. You start by coding a classic users table with password hashing, then add a basic role system.

Then come the first “real” B2B enterprise clients (major accounts, banks, public institutions). Their security requirements land on your desk:

  • “We want to connect with our own SSO (Azure AD / Okta).”
  • “Your data must be fully isolated; we mandate strict data boundaries.”
  • “How do you handle identity isolation and GDPR compliance?”

That’s when the house of cards collapses. Rewriting an identity engine at this stage costs months of engineering and exposes you to major security vulnerabilities.

As a former CTO having led critical architectures (IDPosition, French National Authority for Health), my philosophy is clear: “Think right, structure well, deliver better”. To solve this problem permanently, choosing a robust, open-source, and standardized Identity Provider (IdP) is mandatory. Keycloak is that standard.

Here is the architectural guide for designing an “Enterprise-grade” identity foundation.


1. Architectural Choice: Single Realm vs Multi-Realms

The first structural decision in Keycloak concerns multi-tenancy management. Two main approaches compete, with major trade-offs in security, maintenance, and scalability.

Option A: The “Multi-Realms” Model (Maximum Security Choice)

Each client (tenant) has its own dedicated Keycloak Realm.

  • Pros:
    • Absolute isolation at the Keycloak database level.
    • Each tenant can configure its own Identity Providers (3rd-party IdPs), password rules (mandatory MFA), and custom login themes.
    • GDPR-compliant by design: deleting a tenant equals deleting its dedicated realm.
  • Cons:
    • Operational complexity at scale (managing 500 realms requires strict automation via REST API or Terraform/GitOps).
    • Higher Keycloak resource consumption (RAM).

Option B: The “Single Realm with Groups/Attributes” Model

All users across all tenants share the same Realm, partitioned via Keycloak groups or user attributes.

  • Pros:
    • Simple to administer.
    • Optimal initial boot performance (lower memory footprint).
  • Cons:
    • Risk of data leakage (a single bug in application code could expose users from another tenant).
    • Limited customization for enterprise clients (custom SAML/OIDC are difficult to isolate).

Former CTO’s Feedback: Here is a simple golden rule, summarized in a single key question: “Should a user be able to navigate between your applications using the same session (SSO), or is each client a completely isolated environment requiring its own users, rules, and administrators?”

How to decide immediately using this question:

  • Choose a Single Realm (with Clients or the Organizations feature) if you want your users to log in just once (SSO) or if you wish to centralize configuration (LDAP, MFA, themes).
  • Choose Multi-Realm if you sell your SaaS to corporate clients requiring absolute isolation (no user sharing, client-specific password policies, or fully independent delegated administration), even if it means sacrificing SSO between them.

2. Industrial Deployment: Kubernetes, Helm & GitOps

Deploying Keycloak via “click-ops” on a manual virtual machine is unacceptable for production. Keycloak must be treated as Infrastructure as Code (IaC).

  • Orchestration: Kubernetes (GKE on Google Cloud or Scaleway for European digital sovereignty).
  • Packaging: Helm Charts to standardize provisioning.
  • CI/CD: ArgoCD (GitOps) to synchronize infrastructure state directly from your private Git repository.
# Unified Helm configuration sample for ArgoCD (simplified values.yaml)
keycloak:
  replicaCount: 3 # High availability
  database:
    vendor: postgres
    host: postgres-ha-pool
  ingress:
    enabled: true
    rules:
      - host: auth.your-saas.com

New Tenant Provisioning Pipeline:

  1. The SaaS application issues an automated API request to Keycloak.
  2. A Python script automates the creation of the dedicated Realm.
  3. Standard configuration template import (default roles, theme, OIDC clients).
  4. DNS generation and Cloudflare integration for DDoS protection.

3. Security: Custom Flows & Infrastructure Hardening

Keycloak allows overriding default authentication flows. To optimize UX while maintaining maximum security:

  • Eliminate simple passwords for administrators and enforce WebAuthn (Passkeys / Biometrics) or temporary Magic Links via email.
  • Configure conditional flows: if an IP address leaves the client company’s VPN, Keycloak instantly demands a second authentication factor (MFA).

Cloudflare WAF Shield

Never leave Keycloak endpoints (/auth) exposed directly to the public web without protection. Cloudflare must be placed upstream to:

  • Filter malicious payloads via WAF.
  • Block brute-force attacks on login forms.
  • Rate limit sensitive authentication endpoints.

4. The Scale Trap: Keycloak + OpenFGA (Dual-Layer RBAC/ReBAC)

This is where the difference between amateur architecture and professional engineering is made.

The Problem: JWT Token Bloat (RPT)

Keycloak excels at authentication (who the user is) and macro authorization (RBAC: is the user “Admin” or “User”). However, if you attempt to manage fine-grained permissions (ReBAC: “Nicolas can edit document X only if document X belongs to folder Y for which he has access”), you will bloat the JWT access token.

The token (RPT - Requesting Party Token) becomes massive, exceeds HTTP header size limits on web servers (often 8 KB), and triggers unexplained connection failures for your most active users.

The Solution: Dual-Layer Architecture

[User] -> Authentication -> [ KEYCLOAK ] (Generates compact macro JWT)
                                  |
                                  v (On-the-fly fine-grained verification)
[ SaaS API ] <-------------> [ OpenFGA ] (Relationship Engine / ReBAC)
  1. Keycloak manages global authentication and issues a lean JWT token containing only tenant ID, user ID, and macro roles.
  2. OpenFGA (Fine-Grained Authorization, based on Google’s Zanzibar model) checks fine-grained resource permissions on-the-fly.
  3. To bridge both seamlessly, implement a plugin such as keycloak-openfga-event-publisher to stream user and role events in real-time from Keycloak into OpenFGA.

Conclusion: 3 Golden Rules for IAM Migration Success

  1. Design for isolation on day one: Multi-realm requires discipline, but it is your single biggest credibility asset with enterprise buyers.
  2. Automate everything: If you configure a realm by hand in production, your architecture is not scalable.
  3. Separate authentication from fine-grained authorization: Let Keycloak manage identity, and delegate complex permission trees to a dedicated engine like OpenFGA.
#Keycloak #IAM #SaaS #Kubernetes #OpenFGA #GitOps
Nicolas BAUD

Nicolas BAUD

Senior Software Architect & Eco-design Expert

Expert en solutions technologiques et transformation digitale, Nicolas BAUD accompagne les entreprises dans l'adoption réfléchie de l'IA et de l'automatisation.

Table of Contents