
September 11, 2026
11 min read
By Kokil Thapa | Last reviewed: September 2026
Keycloak: Open-Source Identity and Access solves a problem every multi-app stack hits eventually. You need one place for users, roles, SSO, and token issuance instead of duplicating login logic in every Laravel app, WordPress site, and internal tool. Keycloak is a self-hosted identity provider built on open standards — OAuth 2.0, OpenID Connect, and SAML — and it fits teams that want control without per-seat SaaS fees. This guide covers architecture, production setup, Laravel integration, and honest trade-offs against Laravel-native auth patterns and commercial IdPs.
What is Keycloak and how does open-source identity and access work?
Keycloak is an identity and access management (IAM) server originally from Red Hat and now maintained under the CNCF. It acts as an identity provider (IdP). Users authenticate once against Keycloak. Your applications trust tokens Keycloak signs rather than storing passwords themselves.
That separation matters on real client projects. A law-firm portal, an admin dashboard, and a public marketing site can share one user directory. Role changes happen in one admin console. Revoking access takes effect across every connected client.
Keycloak speaks protocols your stack already understands:
- OpenID Connect (OIDC) — built on OAuth 2.0; best fit for modern web and mobile apps.
- OAuth 2.0 — authorisation flows for APIs and machine clients.
- SAML 2.0 — common in enterprise and legacy integrations.
- Social and brokered login — Google, GitHub, LDAP, Active Directory as upstream sources.
Core concepts you must understand
Keycloak organises everything inside a realm. Think of a realm as a tenant. Production usually means one realm per environment or per product line, not one giant realm for unrelated clients.
Within a realm you define:
- Users — local accounts or federated from LDAP.
- Clients — applications that request tokens (web app, API, CLI).
- Roles — realm roles and client roles mapped into JWT claims.
- Identity providers — upstream IdPs for social or enterprise login.
Tokens carry claims your resource server validates. Access tokens are short-lived. Refresh tokens extend sessions under policy you control. For API-heavy stacks, pair Keycloak with proper API rate limiting and abuse prevention at the gateway layer.
How do you install and run Keycloak in production?
Keycloak runs on Java (Quarkus-based since major version 17+). The supported path in 2026 is the official container image with an external database. Do not rely on the embedded H2 database outside local dev.
Quick start with Docker Compose
For a lab or staging stack on Ubuntu, a minimal Compose file looks like this:
services:
postgres:
image: postgres:18
environment:
POSTGRES_DB: keycloak
POSTGRES_USER: keycloak
POSTGRES_PASSWORD: ${KC_DB_PASSWORD}
volumes:
- kc_pg_data:/var/lib/postgresql/data
keycloak:
image: quay.io/keycloak/keycloak:latest
command: start --optimized
environment:
KC_DB: postgres
KC_DB_URL: jdbc:postgresql://postgres:5432/keycloak
KC_DB_USERNAME: keycloak
KC_DB_PASSWORD: ${KC_DB_PASSWORD}
KC_HOSTNAME: auth.example.com
KC_PROXY: edge
KEYCLOAK_ADMIN: admin
KEYCLOAK_ADMIN_PASSWORD: ${KC_ADMIN_PASSWORD}
ports:
- "8080:8080"
depends_on:
- postgres
volumes:
kc_pg_data: Run the build step once after setting features:
docker compose run --rm keycloak build
docker compose up -d Put Nginx or Apache in front with TLS. Terminate HTTPS at the proxy and set KC_PROXY=edge so Keycloak generates correct redirect URLs. On servers I maintain, this mirrors how we front other Java and PHP services — same Linux system administration patterns, different upstream port.
Production checklist
- Use PostgreSQL 18 or MySQL 9.7 — not embedded H2.
- Run
buildwith only the features you need to shrink attack surface. - Store admin and DB passwords in a secrets manager, not plain Compose files.
- Enable health endpoints and wire them to your monitoring stack.
- Schedule database backups alongside your application dumps.
- Pin image tags in production instead of
latest.
Resource planning: allocate at least 2 GB RAM for a small realm. Heavier federation or brute-force traffic needs more headroom. Budget Rs 3,000–8,000/month (~USD 22–60) for a modest VPS if you self-host everything — often cheaper than per-user SaaS at scale.
How do you integrate Keycloak with Laravel and existing applications?
I use Laravel Sanctum and Passport regularly for first-party API auth. Keycloak enters when you need SSO across multiple apps, external partners, or a central user directory that outlives any single codebase. The integration path is OpenID Connect.
Register a Laravel client in Keycloak
- Create a realm (e.g.
production). - Add a client with type OpenID Connect.
- Set Standard flow for browser login; enable Direct access grants only if you truly need password grants (prefer auth code + PKCE).
- Add valid redirect URIs:
https://app.example.com/auth/callback. - Copy the client ID and secret into Laravel
.env.
Install a maintained OIDC package via Composer 2.10:
composer require socialiteproviders/keycloak Configure config/services.php:
'keycloak' => [
'client_id' => env('KEYCLOAK_CLIENT_ID'),
'client_secret' => env('KEYCLOAK_CLIENT_SECRET'),
'redirect' => env('KEYCLOAK_REDIRECT_URI'),
'base_url' => env('KEYCLOAK_BASE_URL'),
'realms' => env('KEYCLOAK_REALM', 'production'),
], Map Keycloak roles to Laravel gates or Spatie Permission roles on login. A common pattern I've seen on production Laravel applications: store the Keycloak sub claim as an external ID, sync roles from token claims, and keep local profile fields in your database.
Protecting APIs with JWT validation
For stateless APIs, validate JWT access tokens on every request. Fetch the realm public keys from the JWKS endpoint:
GET https://auth.example.com/realms/production/protocol/openid-connect/certs Verify issuer, audience, expiry, and signature in middleware before your controller runs. Never trust client-side role checks alone. This aligns with least-privilege access principles even outside AWS — narrow scopes and short token lifetimes reduce blast radius.
For document portals and client-facing apps — like the secure portals in our Mijar Law Associates portfolio work — central IAM plus server-side authorisation beats rolling custom OAuth from scratch.
Keycloak vs Laravel Sanctum vs Auth0: which should you choose?
Pick based on scope, team size, and operational appetite — not hype.
| Criteria | Keycloak (self-hosted) | Laravel Sanctum / Passport | Auth0 / Okta (SaaS) |
|---|---|---|---|
| Best for | Multi-app SSO, on-prem, full control | Single Laravel app or API | Fast launch, minimal ops |
| Protocols | OIDC, OAuth 2.0, SAML | OAuth 2.0 (Passport), session/cookie (Sanctum) | OIDC, SAML, enterprise features |
| Ops burden | You run patches, HA, backups | Low — ships with Laravel | Vendor-managed |
| Cost model | Infrastructure + your time | Free (MIT) | Per MAU / enterprise pricing |
| User federation | LDAP, AD, social brokering | Custom only | Built-in connectors |
| Vendor lock-in | Low — open source | Low | Medium to high |
Verdict: stay on Sanctum for a lone Laravel 13 app with simple token needs. Choose Keycloak when two or more applications must share login, when SAML is required, or when compliance demands self-hosting. Choose Auth0 when speed beats control and budget allows per-user fees.
On enterprise application development engagements, I recommend Keycloak when the roadmap includes a mobile app, partner API, and admin portal — three clients, one identity layer.
How do you secure Keycloak realms, clients, and tokens in production?
Running an IdP makes Keycloak a high-value target. Treat it like a database containing credentials.
Realm and client hardening
- Disable unused realms and clients. Every client is an OAuth surface.
- Prefer confidential clients with secrets for server-side Laravel apps.
- Use public clients with PKCE only for SPAs — never embed secrets in JavaScript.
- Restrict redirect URIs to exact paths. Wildcards cause open redirect bugs.
- Enable brute-force detection and sensible lockout thresholds.
- Turn off legacy flows: implicit flow, direct access grants unless strictly required.
Token and session policy
Short access token lifetimes (5–15 minutes) limit stolen token damage. Refresh tokens should rotate on use. Define session idle and max timeouts per realm. Map only the roles you need into tokens — bloated JWTs leak information and bloat headers.
Generate strong client secrets. Store them in environment variables, not Git. Our password generator tool helps for initial secrets, but use a dedicated secrets manager for production rotation.
Network and admin access
Never expose the Keycloak admin console to the public internet without IP restriction or VPN. Put admin tasks behind a bastion or internal network. Enable audit logging and ship logs to your SIEM or at minimum a persistent log store.
These practices overlap with identity federation across cloud providers — the IdP is the trust anchor regardless of where workloads run.
How do you deploy Keycloak with high availability and upgrades?
Single-node Keycloak is fine for staging. Production needs a plan before the first user lands.
High availability pattern
Run two or more Keycloak nodes behind a load balancer. Point all nodes at the same PostgreSQL database. Enable sticky sessions only if your setup requires it — OIDC flows are mostly stateless at the app layer. Use Redis 8.10 or Infinispan for distributed caching when Keycloak documentation recommends it for your version.
Health checks on /health/ready keep bad nodes out of rotation. Test failover by killing a pod and confirming login still works.
Upgrade strategy
Read the upstream release notes before every upgrade. Export realm JSON as backup. Upgrade staging first. Run the new image tag, apply database migrations automatically on boot, and smoke-test login flows for each client.
If you run Keycloak alongside Laravel apps on the same infrastructure, coordinate maintenance windows. A broken IdP takes down every dependent app — plan rollback images and database snapshots.
For teams without dedicated DevOps, managed hosting or a simplified single-node setup with aggressive backups beats a fragile HA cluster nobody monitors. Honest ops capacity matters as much as feature lists.
Key Takeaways
- Keycloak centralises login, SSO, and token issuance via OIDC, OAuth 2.0, and SAML — ideal when multiple apps share users.
- Run it on PostgreSQL with TLS, pinned images, and secrets outside Git; never use embedded H2 in production.
- Integrate Laravel through OIDC authorization code + PKCE; validate JWTs server-side on every API request.
- Prefer Sanctum for single-app auth; pick Keycloak when SSO, SAML, or self-hosting requirements appear.
- Lock down admin access, shorten token lifetimes, and restrict redirect URIs — an IdP breach compromises everything downstream.
- Plan HA, backups, and tested upgrades before go-live; Keycloak downtime equals application downtime.
People Also Ask
Is Keycloak really free for commercial use?
Yes. Keycloak is Apache License 2.0 software. You can use it in commercial products without license fees. Your costs are infrastructure, backups, monitoring, and the engineering time to run and upgrade it — not per-user SaaS billing.
Can Keycloak replace Laravel Breeze or Fortify?
For a standalone Laravel app with no external SSO needs, Breeze or Fortify is simpler. Keycloak replaces them when you need central identity across several applications or federation with LDAP and SAML systems your client already operates.
Does Keycloak support multi-factor authentication?
Keycloak includes built-in OTP (TOTP), WebAuthn, and configurable authentication flows. You can require MFA per realm, per client, or conditionally via custom authenticators — useful for admin and client portals handling sensitive documents.
How does Keycloak compare to cloud IAM like AWS Cognito?
Cognito integrates tightly with AWS services and charges per MAU. Keycloak runs anywhere — on-prem, VPS, or Kubernetes — and avoids cloud vendor lock-in. Teams on multi-cloud or self-managed VPS infrastructure often pick Keycloak for portability. See also workload identity without long-lived keys for machine-to-machine patterns in cloud environments.
Ship centralised identity without reinventing OAuth
Keycloak: Open-Source Identity and Access earns its place when your product grows past one login form on one codebase. You get standards-based SSO, federation, and token policies under your control. The trade-off is operational responsibility — patches, uptime, and security hardening land on your team.
Start with a staging realm, wire one Laravel client, and prove the OIDC flow before migrating production users. Export realm config to JSON and treat it like application code. If you want help designing IAM for a multi-app stack — Laravel API, client portal, and mobile — API development and custom software development engagements are where I usually embed this work.
Ready to centralise auth for your next platform? Contact us to discuss architecture, or browse the open-source contribution guide if you plan to upstream fixes. Strong identity design starts before user number ten — not after the second app ships.
Frequently Asked Questions
0 Comments
Leave a comment
Your email is not published. Comments appear once they have been read. Sign in to have your details filled in.

