Keycloak SSO Setup: Realm Config, LDAP Integration & OIDC Guide
Keycloak is an open-source Identity and Access Management solution that provides Single Sign-On, OIDC, SAML 2.0, LDAP federation, and fine-grained authorization — all self-hosted with no per-MAU fees. This guide covers Docker quickstart, realm and client configuration, Active Directory integration, and production deployment patterns.
What is Keycloak and When to Use It?
Keycloak is backed by Red Hat (now part of IBM) and is the upstream project for Red Hat Single Sign-On (RH-SSO). It handles user authentication, token issuance, consent flows, and identity federation entirely within your infrastructure. Organizations choose Keycloak over cloud identity providers primarily for data sovereignty (GDPR, HIPAA, FedRAMP), on-premises Active Directory integration, or to avoid the cost scaling of per-MAU pricing at tens of thousands of users.
Keycloak is not the easiest solution to operate — it requires a database, clustering for HA, and regular upgrades. It's most appropriate for enterprise environments with a dedicated DevOps team or for regulated industries where cloud identity providers are not permitted.
Docker Quickstart
# Start Keycloak in development mode (NOT for production)
docker run -p 8080:8080 \
-e KEYCLOAK_ADMIN=admin \
-e KEYCLOAK_ADMIN_PASSWORD=admin \
quay.io/keycloak/keycloak:24.0.3 \
start-dev
# Access admin console at http://localhost:8080
# Login with admin / admin # Production-ready Docker with Postgres
docker run -p 8443:8443 \
-e KC_DB=postgres \
-e KC_DB_URL=jdbc:postgresql://postgres:5432/keycloak \
-e KC_DB_USERNAME=keycloak \
-e KC_DB_PASSWORD=secret \
-e KC_HOSTNAME=auth.yourcompany.com \
-e KC_PROXY=edge \
-e KEYCLOAK_ADMIN=admin \
-e KEYCLOAK_ADMIN_PASSWORD=StrongPassword123! \
quay.io/keycloak/keycloak:24.0.3 \
start Realm and Client Configuration
After login, create a new realm (avoid using the 'master' realm for applications — it's for Keycloak administration only). Within your realm, create clients for each application:
# Create realm and client via Keycloak Admin CLI
# (kcadm.sh is bundled in the Docker image)
# Authenticate
/opt/keycloak/bin/kcadm.sh config credentials \
--server http://localhost:8080 \
--realm master \
--user admin --password admin
# Create realm
/opt/keycloak/bin/kcadm.sh create realms \
-s realm=myapp \
-s enabled=true
# Create OIDC client
/opt/keycloak/bin/kcadm.sh create clients -r myapp \
-s clientId=myapp-frontend \
-s publicClient=true \
-s 'redirectUris=["https://app.yourcompany.com/*"]' \
-s 'webOrigins=["https://app.yourcompany.com"]' User Federation with LDAP / Active Directory
Navigate to User Federation > Add ldap provider. Key settings for Active Directory:
| Setting | Value |
|---|---|
| Vendor | Active Directory |
| Connection URL | ldaps://your-ad-server:636 |
| Users DN | ou=Users,dc=corp,dc=com |
| Bind DN | cn=svc-keycloak,ou=Service,dc=corp,dc=com |
| Sync mode | FORCE (overwrite Keycloak with LDAP) |
OIDC Flow Setup and Token Inspection
# OIDC Discovery endpoint (provides all config automatically)
curl https://auth.yourcompany.com/realms/myapp/.well-known/openid-configuration
# Token endpoint — exchange authorization code for tokens
curl -X POST https://auth.yourcompany.com/realms/myapp/protocol/openid-connect/token \
-d grant_type=authorization_code \
-d code=AUTH_CODE \
-d redirect_uri=https://app.yourcompany.com/callback \
-d client_id=myapp-frontend
# Introspect a token
curl -X POST https://auth.yourcompany.com/realms/myapp/protocol/openid-connect/token/introspect \
-d token=ACCESS_TOKEN \
-u myapp-backend:client_secret Protecting a Node.js API
// npm install keycloak-connect express-session
const Keycloak = require('keycloak-connect');
const session = require('express-session');
const memoryStore = new session.MemoryStore();
app.use(session({
secret: 'some secret',
resave: false,
saveUninitialized: true,
store: memoryStore
}));
const keycloak = new Keycloak({ store: memoryStore }, {
realm: 'myapp',
'auth-server-url': 'https://auth.yourcompany.com',
'ssl-required': 'external',
resource: 'myapp-backend',
credentials: { secret: 'your-client-secret' }
});
app.use(keycloak.middleware());
// Protect route — requires authentication
app.get('/api/protected', keycloak.protect(), (req, res) => {
res.json({ message: 'Authenticated!', user: req.kauth.grant.access_token.content });
});
// Protect route — requires role
app.get('/api/admin', keycloak.protect('realm:admin'), (req, res) => {
res.json({ message: 'Admin access granted' });
}); Keycloak vs Auth0 vs Authentik
| Feature | Keycloak | Auth0 | Authentik |
|---|---|---|---|
| Hosting | Self-hosted | Cloud (SaaS) | Self-hosted |
| Pricing | Free (OSS) | Per MAU | Free (OSS) |
| LDAP/AD Federation | Excellent | Good | Good |
| Admin UI | Complex | Excellent | Modern, clean |
| Ops complexity | High | Low | Medium |
Related Products
on GumroadDeveloper Productivity Bundle
Stop rebuilding the same setup every project. 51 VSCode snippets, 40 Git aliases, 5 Docker Compose stacks, 5 GitHub Actions workflows, 5 README templates, and a dotfiles kit. Set up a professional dev environment in under an hour.
Buy on Gumroad →AI Prompt Engineering Toolkit
58 structured prompt templates for Claude, ChatGPT, and Gemini — organized by use case. Code Review, Debugging, Documentation, Architecture, and 10 model-specific tips. Stop writing prompts from scratch.
Buy on Gumroad →Developer Cheat Sheet Bundle
10 print-ready cheat sheets for the tools developers use every day: Git, Docker, Linux CLI, SQL, Regex, HTTP Status codes, VS Code shortcuts, Bash scripting, jq/JSON, and Markdown.
Buy on Gumroad →You Might Also Need
JSON Formatter & Validator
Format, beautify, and validate JSON online. Paste your JSON to instantly pretty-print it with 2-space, 4-space, or tab indentation. Minify JSON too. Free, runs in your browser.
Open free tool →
Regex Tester
Free regex tester. Test regular expressions against multiple strings with expected match/no-match assertions — see instant pass/fail results. Built-in presets for email, URL, IPv4, and phone. Pro: unl
Open free tool →
Base64 Encoder & Decoder
Free Base64 Encoder & Decoder. Convert text, images, and any file to Base64 and back. Supports URL-safe Base64, image data URIs, and file download from Base64. Runs 100% in your browser — no data sent
Open free tool →
More Free Tools
Related Articles
curl 深度使用手冊:API 測試從入門到進階
curl 是每位開發者必備的 CLI 工具。本文涵蓋 GET/POST/PUT/DELETE 請求、認證、header 設定、檔案上傳、除錯技巧,以及 REST API 測試的完整實戰範例。
Best AI Code Review Tools 2026: CodeRabbit, Sourcery, DeepCode & Bito Compared
Compare top AI code review tools for 2026: CodeRabbit, Sourcery, DeepCode, and Bito. Features, pricing, GitHub/GitLab integration, and choosing the right tool for your team.
AI Code Review Tools 2026: GitHub Copilot, CodeRabbit, Qodo Merge Ranked
Compare AI code review tools for 2026: GitHub Copilot code review, CodeRabbit, Qodo Merge, Sourcery, and PR-Agent. Pricing, accuracy, and GitHub integration.
AI Coding Tools Comparison 2026: GitHub Copilot vs Cursor vs Windsurf vs Cline
Comprehensive comparison of the best AI coding tools in 2026: GitHub Copilot, Cursor, Windsurf, and Cline. Pricing, features, model support, and real-world benchmarks.
AI Pair Programming in 2026: GitHub Copilot vs Cursor vs Claude Code
Master AI pair programming in 2026. Compare GitHub Copilot, Cursor, and Claude Code for autocomplete, chat, and agentic workflows. Includes setup guides and productivity tips.
Enjoying this tool? Get more like it.
Weekly developer tool guides, productivity playbooks & AI tricks. Free. No spam.
Unlock AI-Powered Dev Tools
- ⚡ AI Code Review, Doc Generator & SQL Builder
- ⚡ All premium templates & early access
- ⚡ Member discounts on Gumroad products
$9/mo after trial · Cancel anytime
Want the full toolkit?
Get DevPlaybook Pro
Every template, guide, boilerplate, and automation script in one bundle. 13 premium products — grab them all at once and save big.
MIT licensed · Instant download · No subscription
See what's included → Browse all deals →