Security · Nov 25, 2026 · 11 min read

Keycloak 24 with Auth.js v5: SSO, RBAC & Multi-Tenancy Guide

Hands-on tutorial for integrating Keycloak 24 as an identity provider with Auth.js v5 in Next.js applications. Covers Docker setup, realm configuration, role mapping, multi-tenancy strategies, product

Keycloak 24 with Auth.js v5: SSO, RBAC & Multi-Tenancy Guide

Running Keycloak 24 with Docker Compose

Keycloak 24 uses a Quarkus-based distribution that starts significantly faster than previous WildFly versions. Begin by creating a docker-compose.yml file with the following configuration for local development:

version: '3.9'
services:
  keycloak:
    image: quay.io/keycloak/keycloak:24.0.4
    command: start-dev --import-realm
    environment:
      KC_DB: postgres
      KC_DB_URL: jdbc:postgresql://postgres:5432/keycloak
      KC_DB_USERNAME: keycloak
      KC_DB_PASSWORD: keycloak
      KC_HOSTNAME: localhost
      KEYCLOAK_ADMIN: admin
      KEYCLOAK_ADMIN_PASSWORD: admin123
    ports:
      - "8080:8080"
    depends_on:
      - postgres

  postgres:
    image: postgres:16.2
    environment:
      POSTGRES_DB: keycloak
      POSTGRES_USER: keycloak
      POSTGRES_PASSWORD: keycloak
    volumes:
      - postgres_data:/var/lib/postgresql/data

volumes:
  postgres_data:

The start-dev flag enables development features including hot reloading of themes and automatic database schema updates. For production you must replace this with build followed by start to create an optimized immutable image. The PostgreSQL dependency is essential because the default in-memory H2 database loses all data on restart and cannot support clustering.

Run docker compose up -d and wait approximately 25 seconds for the initial bootstrap. Access the admin console at http://localhost:8080/admin. Log in with the credentials defined in KEYCLOAK_ADMIN. The first action after login should be changing the administrator password to a strong value longer than 16 characters.

Trade-off: Using PostgreSQL from day one adds operational complexity but prevents painful data migration later. The Quarkus distribution consumes roughly 180 MB of heap at idle compared to over 400 MB in older WildFly releases.

Creating Realms for Isolation

Realms are the top-level isolation boundary in Keycloak. Each realm maintains its own set of users, clients, roles, and identity providers. For most SaaS products a single master realm plus one application realm is sufficient. Create a new realm named saas-prod through the admin console dropdown.

Import the following partial realm configuration JSON to establish baseline settings:

{
  "realm": "saas-prod",
  "enabled": true,
  "sslRequired": "external",
  "accessTokenLifespan": 300,
  "accessTokenLifespanForImplicitFlow": 900,
  "ssoSessionIdleTimeout": 1800,
  "ssoSessionMaxLifespan": 36000,
  "offlineSessionIdleTimeout": 2592000,
  "bruteForceProtected": true,
  "permanentLockout": false,
  "maxFailureWaitSeconds": 60,
  "minimumQuickLoginWaitSeconds": 60
}

The accessTokenLifespan of 300 seconds (5 minutes) follows current OAuth2 security recommendations to limit the window of exposure if a token is compromised. The bruteForceProtected setting automatically temporarily locks accounts after repeated failed login attempts. These values can be adjusted later but should be set early because some values affect token signatures and require client re-registration.

After creation, navigate to Realm Settings → Tokens and enable "Revoke refresh token" with a refresh token max reuse of 0. This forces rotation on every use and mitigates replay attacks.

Client Configuration for Next.js Applications

Inside the saas-prod realm, create an OpenID Connect client named nextjs-frontend. Set the client type to "OpenID Connect" and access type to "confidential". Enable "Client protocol mapper" for "audience" and add the client ID itself to the audience claim.

Valid redirect URIs should be restrictive:

  • http://localhost:3000/api/auth/callback/keycloak
  • https://yourdomain.com/api/auth/callback/keycloak

Web origins should be set to + only during development. In production list explicit origins to prevent unauthorized CORS requests. Generate a client secret and store it securely. Never commit this value to version control.

Under Client Scopes, create a new "roles" scope and add a "Realm roles" mapper that includes the claim roles in both ID and access tokens. This mapper determines how role information travels to your application.

Trade-off: Confidential clients require a backend to exchange the authorization code for tokens, which Auth.js handles automatically. Public clients (SPA mode) eliminate the need for a client secret but increase exposure to token theft via XSS if your CSP is weak.

Mapping Roles and Custom Claims

Keycloak supports realm roles and client roles. For most applications, define roles at the realm level (admin, tenant_owner, user) and then map them into the token. Create these three roles in the realm.

Add a user through the Users section and assign the user role. For the admin user, assign both admin and tenant_owner.

To include tenant information, add a custom user attribute called tenant_id with value acme-corp. Create a protocol mapper of type "User Attribute" that maps this attribute to a token claim named tenant with type String. This claim will be available in the JWT and can be used for database row-level security or application-level filtering.

Verify the token contents by using the "Evaluate" tab in the client configuration. The resulting access token should contain:

{
  "typ": "Bearer",
  "azp": "nextjs-frontend",
  "roles": ["user", "tenant_owner"],
  "tenant": "acme-corp",
  "email": "admin@example.com"
}

Integrating Auth.js v5 with the Keycloak Provider

Auth.js v5 uses a new file-based route handler at app/api/auth/[...nextauth]/route.ts. Install the required packages:

npm install next-auth@beta @auth/core
npm install --save-dev @types/node

Create the route handler with the following configuration:

import NextAuth from "next-auth";
import Keycloak from "next-auth/providers/keycloak";

export const { handlers, auth, signIn, signOut } = NextAuth({
  providers: [
    Keycloak({
      clientId: process.env.KEYCLOAK_CLIENT_ID!,
      clientSecret: process.env.KEYCLOAK_CLIENT_SECRET!,
      issuer: process.env.KEYCLOAK_ISSUER!,
    }),
  ],
  callbacks: {
    async jwt({ token, account, profile }) {
      if (account) {
        token.accessToken = account.access_token;
        token.idToken = account.id_token;
        token.refreshToken = account.refresh_token;
      }
      if (profile) {
        token.roles = profile.roles || [];
        token.tenant = profile.tenant;
      }
      return token;
    },
    async session({ session, token }) {
      session.user.id = token.sub!;
      session.user.roles = token.roles as string[];
      session.user.tenant = token.tenant as string;
      session.accessToken = token.accessToken as string;
      return session;
    },
  },
  session: {
    strategy: "jwt",
    maxAge: 60 * 30, // 30 minutes
  },
  pages: {
    signIn: "/auth/signin",
  },
});

The jwt callback extracts roles and tenant information from the profile returned by Keycloak. The session callback makes these values available to React components via the useSession hook. Using JWT strategy avoids an extra database roundtrip on every request compared to database sessions, but you lose the ability to instantly revoke sessions server-side.

Store the following values in your .env.local:

KEYCLOAK_CLIENT_ID=nextjs-frontend
KEYCLOAK_CLIENT_SECRET=your-long-secret-here
KEYCLOAK_ISSUER=http://localhost:8080/realms/saas-prod

Protecting Routes and API Endpoints

With the session populated, protect server components and route handlers using the auth() helper exported from the configuration file.

Example protected server component:

import { auth } from "@/auth";

export default async function Dashboard() {
  const session = await auth();
  
  if (!session?.user) {
    return 

Access denied.

; } const isAdmin = session.user.roles?.includes("admin"); return ( <div> <h1>Welcome, {session.user.email}</h1> {isAdmin && <AdminPanel />} </div> ); }

For API routes, the same auth() function works inside route handlers. Always validate the tenant claim against the requested resource to prevent data leakage between customers. A simple middleware can enforce role requirements for entire route segments:

export async function middleware(request: NextRequest) {
  const session = await auth();
  const pathname = request.nextUrl.pathname;
  
  if (pathname.startsWith("/admin") && 
      !session?.user?.roles?.includes("admin")) {
    return NextResponse.redirect(new URL("/unauthorized", request.url));
  }
  
  return NextResponse.next();
}

Multi-Tenancy Strategies: Realms vs Custom Attributes

Two primary approaches exist for multi-tenancy with Keycloak. The first uses a separate realm per tenant. This provides strong isolation because users, clients, and roles cannot cross realms. However, managing updates across hundreds of realms becomes operationally expensive. Realm creation can be automated via the Keycloak Admin REST API using a service account with realm-management permissions.

The second, more scalable approach uses a single realm with a tenant claim as shown earlier. Your application code then filters all database queries by this tenant identifier. When using PostgreSQL, combine this with Row Level Security (RLS) policies that automatically add tenant_id = current_setting('app.current_tenant') to every query.

Trade-offs:

  • Separate realms: Stronger isolation, easier compliance audits, higher operational overhead.
  • Single realm + tenant claim: Simpler management, easier to implement SSO across tenants, requires rigorous application-level enforcement.

For most startups the single-realm approach with strict backend filtering is sufficient until you reach approximately 500 enterprise customers with unique compliance needs.

Adding Identity Brokering for Social and Enterprise Logins

Keycloak excels at identity brokering. In the Identity Providers section, add Google, GitHub, and Microsoft providers using OAuth2. For enterprise customers, configure SAML 2.0 or OIDC connections to their identity systems.

Each broker can be assigned a unique alias. When a user logs in through a broker, Keycloak creates a federated identity link. Subsequent logins can be configured to automatically link accounts based on email address matching. Enable "First Login Flow" to force users to complete any missing profile information on their first social login.

LDAP integration follows a similar pattern. Configure an LDAP provider pointing to Active Directory or OpenLDAP. Map LDAP attributes to Keycloak user attributes and synchronize roles using a custom script mapper if group membership determines permissions.

Production Deployment and Clustering

For production, build an optimized Keycloak image without the dev features:

docker run --rm \
  -e KC_DB=postgres \
  -e KC_DB_URL=jdbc:postgresql://db.example.com:5432/keycloak \
  -e KC_DB_USERNAME=keycloak \
  -e KC_DB_PASSWORD=strongpassword \
  -e KC_HOSTNAME=auth.example.com \
  -e KC_PROXY=edge \
  quay.io/keycloak/keycloak:24.0.4 build

Then run multiple instances behind a load balancer. All instances must share the same PostgreSQL database and an Infinispan cache for distributed sessions. Enable sticky sessions at the load-balancer level or use the built-in distributed cache.

Use a reverse proxy such as Traefik or Nginx with automatic Let's Encrypt certificates. Set KC_PROXY=edge so Keycloak correctly generates HTTPS callback URLs. Disable the built-in Keycloak management console in production by setting KC_HTTP_MANAGEMENT_PORT to an internal-only interface.

Observability with Prometheus and Structured Logging

Keycloak 24 exposes metrics at /metrics when you enable the feature with --features=metrics. The Prometheus endpoint provides counters for login attempts, active sessions, and JVM heap usage. A basic scrape configuration looks like:

scrape_configs:
  - job_name: keycloak
    metrics_path: /metrics
    static_configs:
      - targets: ['auth.example.com:8080']

Configure JSON logging with KC_LOG_LEVEL=INFO and KC_LOG_FORMAT=json. Forward logs to Loki or ELK stack for correlation with application logs using the trace ID that Keycloak includes in every response header when tracing is enabled.

Alert rules worth setting up immediately:

  • Login failure rate > 5% over 5 minutes
  • Number of active sessions > 80% of configured limit
  • Database connection pool exhaustion

Security Hardening Checklist

Beyond the defaults, apply these additional measures:

  1. Enable "Secure" and "HttpOnly" flags on all cookies by setting KC_SPI_COOKIE_SECURE=true.
  2. Configure Content-Security-Policy headers at the reverse proxy level that do not allow inline scripts.
  3. Set password policies requiring minimum 14 characters, one uppercase, one number, and 90-day expiration for admin accounts.
  4. Enable "OAuth 2.0 Device Authorization Grant" only if you have IoT use cases; otherwise disable unnecessary flows.
  5. Regularly rotate the realm signing keys through the Keys tab. Keycloak supports automatic key rotation with a grace period for old tokens.
  6. Use short-lived access tokens (5 minutes) combined with refresh token rotation.

Regularly scan your Keycloak instance with tools like OWASP ZAP or Nuclei using the Keycloak-specific templates to catch misconfigurations.

Performance Tuning and Scaling Limits

Keycloak performance depends heavily on the database and cache configuration. With PostgreSQL 16 and proper indexing on the user_entity and event_entity tables, a single instance can handle approximately 1200 logins per minute under typical workloads. Adding a second instance with proper cache replication increases this to over 3000 logins per minute.

Monitor the keycloak_jvm_heap and keycloak_login Prometheus metrics. When heap usage consistently exceeds 70%, increase allocated RAM or optimize mappers. Excessive protocol mappers can add 30-50 ms of latency per token generation.

For very high scale (50k+ concurrent sessions), consider using Keycloak's external Infinispan cluster in dedicated mode instead of the embedded cache. This architecture has been shown to reduce session replication overhead by approximately 40% at the cost of additional infrastructure.

Always benchmark your specific authentication flows using tools like k6 or Artillery with realistic user journeys rather than relying on generic published numbers.

Common Pitfalls and Debugging Techniques

The most frequent issue is redirect URI mismatch. Keycloak returns a detailed error page only in development mode. In production, check the server logs for the exact expected versus received URI.

Token signature validation failures often occur after key rotation. Implement a JWKS caching strategy with a 15-minute TTL in Auth.js by setting the jwks option explicitly if the default does not meet your needs.

When roles do not appear in the session, verify that the client scope is assigned to the client and that the mapper is set to "Full group path" for nested groups if you use them.

For silent authentication failures in SPAs, ensure that the prompt=none flow is allowed in the client configuration and that your iframe is not blocked by browser tracking prevention. The recommended pattern is to use the refreshAccessToken callback in Auth.js rather than manual iframe polling.

Database connection leaks appear under load when the PostgreSQL max_connections is set too low relative to Keycloak's pool size. Set Keycloak's KC_DB_POOL_MAX_SIZE to 20 per instance and ensure your PostgreSQL instance can support at least 100 connections total.

This implementation provides a solid foundation that scales from a single-developer MVP to a multi-tenant SaaS serving thousands of daily active users. Each decision documented above includes measured trade-offs between security, operational simplicity, and performance so you can adapt the architecture to your specific constraints.

Keep reading

Related Articles