Kokil Thapa - Professional Web Developer in Nepal
Freelancer Web Developer in Nepal with 15+ Years of Experience

Kokil Thapa is an experienced full-stack web developer focused on building fast, secure, and scalable web applications. He helps businesses and individuals create SEO-friendly, user-focused digital platforms designed for long-term growth.

Keycloak: Open-Source Identity and Access

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.
Keycloak IAM ArchitectureUsersBrowser / MobileKeycloak ServerRealms · Clients · RolesOIDC · OAuth 2 · SAMLApp ALaravel SPAApp BREST APILDAP / ADUser Federation
Keycloak: Open-Source Identity and Access centralises authentication and issues tokens consumed by multiple applications.

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

  1. Use PostgreSQL 18 or MySQL 9.7 — not embedded H2.
  2. Run build with only the features you need to shrink attack surface.
  3. Store admin and DB passwords in a secrets manager, not plain Compose files.
  4. Enable health endpoints and wire them to your monitoring stack.
  5. Schedule database backups alongside your application dumps.
  6. 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

  1. Create a realm (e.g. production).
  2. Add a client with type OpenID Connect.
  3. Set Standard flow for browser login; enable Direct access grants only if you truly need password grants (prefer auth code + PKCE).
  4. Add valid redirect URIs: https://app.example.com/auth/callback.
  5. 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.

OIDC Authorization Code + PKCE FlowUser BrowserLaravel AppKeycloakLogin + ConsentResource API1. Login click2. Auth redirect3. User authenticates4. Code5. Token exchange6. Bearer access token
Authorization code with PKCE is the recommended browser flow when wiring Keycloak to Laravel or SPA frontends.

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.

CriteriaKeycloak (self-hosted)Laravel Sanctum / PassportAuth0 / Okta (SaaS)
Best forMulti-app SSO, on-prem, full controlSingle Laravel app or APIFast launch, minimal ops
ProtocolsOIDC, OAuth 2.0, SAMLOAuth 2.0 (Passport), session/cookie (Sanctum)OIDC, SAML, enterprise features
Ops burdenYou run patches, HA, backupsLow — ships with LaravelVendor-managed
Cost modelInfrastructure + your timeFree (MIT)Per MAU / enterprise pricing
User federationLDAP, AD, social brokeringCustom onlyBuilt-in connectors
Vendor lock-inLow — open sourceLowMedium 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.

IAM Choice Decision TreeNeed central SSO?Single Laravel appMulti-app / SAMLZero ops budgetNoYesNo ops teamSanctumKeycloakAuth0 SaaS
Use this decision tree to pick Keycloak, Laravel Sanctum, or a managed IdP for your stack.

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.

Production Keycloak TopologyTLS Load BalancerKeycloak Node 1Keycloak Node 2Keycloak Node 3PostgreSQL PrimaryNightly backups · Point-in-time recovery
Production Keycloak: Open-Source Identity and Access runs behind a TLS load balancer with shared PostgreSQL storage.

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

Keycloak is a self-hosted identity and access management server maintained under the CNCF. It acts as an identity provider: users authenticate once, and your applications trust tokens Keycloak signs via OAuth 2.0, OpenID Connect, and SAML instead of storing passwords locally. Role changes and access revocation happen in one admin console and apply across every connected client.

Yes. Keycloak is Apache License 2.0 software with no per-user license fees for commercial products.

Budget Rs 3,000–8,000/month (~USD 22–60) for a modest VPS plus your engineering time for patches, backups, and monitoring.

The supported 2026 path is the official Quarkus-based container image with an external database, not embedded H2. Use Docker Compose with PostgreSQL 18, run docker compose run --rm keycloak build once after enabling features, then docker compose up -d. Put Nginx or Apache in front with TLS, set KC_PROXY=edge, and pin image tags instead of using latest. I've seen this mirror standard Linux administration patterns on servers where Java and PHP services share the same proxy setup.

Use PostgreSQL 18 or MySQL 9.7 as an external database. Never rely on the embedded H2 database outside local development. Schedule database backups alongside your application dumps, store DB credentials in a secrets manager rather than plain Compose files, and point all HA nodes at the same PostgreSQL instance when scaling beyond a single server.

A realm is a tenant boundary — production setups usually use one realm per environment or product line, not one giant realm for unrelated apps. Clients are applications that request tokens, such as a Laravel web app, API, or CLI tool. Roles exist at realm level and client level and map into JWT claims your resource server validates. Users may be local accounts or federated from LDAP, Active Directory, or social identity providers configured inside the realm.

Register an OpenID Connect client in your Keycloak realm with Standard flow enabled and valid redirect URIs such as https://app.example.com/auth/callback. Install socialiteproviders/keycloak via Composer 2.10, configure client ID, secret, base URL, and realm in config/services.php, then map Keycloak roles to Laravel gates or Spatie Permission roles on login. Store the Keycloak sub claim as an external ID, sync roles from token claims, and keep local profile fields in your database.

Stay on Sanctum or Passport for a lone Laravel 13 app with simple first-party token needs — the ops burden stays low because auth ships with Laravel. Choose Keycloak when two or more applications must share login, when SAML is required for enterprise integrations, or when compliance demands self-hosting. On engagements where the roadmap includes a mobile app, partner API, and admin portal, a central identity layer beats duplicating login logic in every codebase.

Pick Auth0 or Okta when speed beats control and your budget allows per-MAU SaaS pricing with minimal operational overhead. Choose Keycloak when you need multi-app SSO, on-prem or VPS control, LDAP and Active Directory federation, or low vendor lock-in through open-source standards. Keycloak trades per-user fees for infrastructure cost plus your team's time running patches, HA, and backups.

For a standalone Laravel app with no external SSO needs, Breeze or Fortify remains simpler and easier to maintain. Keycloak replaces them when you need central identity across several applications or federation with LDAP and SAML systems your organisation already operates. The trade-off is operational responsibility — you run the IdP, not Laravel alone.

Yes. Keycloak includes built-in OTP via TOTP, WebAuthn support, and configurable authentication flows. You can require MFA per realm, per client, or conditionally through custom authenticators. That matters for admin consoles and client portals handling sensitive documents where a password alone is insufficient. Combine MFA with brute-force detection and sensible lockout thresholds for defence in depth.

Treat Keycloak like a database containing credentials. Disable unused realms and clients, use confidential clients with secrets for server-side Laravel apps, and restrict redirect URIs to exact paths because wildcards cause open redirect bugs. Set short access token lifetimes of five to fifteen minutes, rotate refresh tokens on use, and map only needed roles into JWTs. Never expose the admin console to the public internet without IP restriction or VPN, enable audit logging, and store client secrets in environment variables or a secrets manager, not Git.

For stateless APIs, validate JWT access tokens on every request before your controller runs. Fetch the realm public keys from the JWKS endpoint at GET https://auth.example.com/realms/production/protocol/openid-connect/certs, then verify issuer, audience, expiry, and signature in middleware. Never trust client-side role checks alone. This aligns with least-privilege access — narrow scopes and short token lifetimes reduce blast radius if a token is stolen.

Run two or more Keycloak nodes behind a TLS load balancer, all pointing at the same PostgreSQL database. Use Redis 8.10 or Infinispan for distributed caching when documentation recommends it for your version, and wire health checks on /health/ready to keep bad nodes out of rotation. Before upgrades, read release notes, export realm JSON as backup, upgrade staging first, smoke-test login for each client, and keep rollback images plus database snapshots ready. Keycloak downtime equals downtime for every dependent application.

Cognito integrates tightly with AWS services and charges per monthly active user. Keycloak runs anywhere — on-prem, VPS, or Kubernetes — and avoids cloud vendor lock-in through portable OIDC, OAuth 2.0, and SAML standards. Teams on multi-cloud setups or self-managed VPS infrastructure often pick Keycloak for portability and predictable infrastructure cost. Cognito wins when your entire stack lives in AWS and you want a managed service with minimal ops burden.

Share this article

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.

Quick Contact Options
Choose how you want to connect me: