Links#
https://www.keycloak.org/documentation
https://www.keycloak.org/docs/latest/server_admin/
https://www.keycloak.org/server/configuration-production
https://www.keycloak.org/server/reverseproxy
https://www.keycloak.org/server/hostname
https://www.keycloak.org/server/containers
https://www.keycloak.org/operator/
https://www.keycloak.org/server/all-config1. Important Points#
Keycloak 适合做企业内部应用的 IdP / IAM 中枢,也适合把 LDAP / AD / 企业上游 IdP / 自研系统接到统一登录入口。
Keycloak can be:
OIDC / OAuth2 authorization server
SAML identity provider
identity broker for upstream IdP
user federation gateway for LDAP / AD
central place for realm / client / role / group / session policy
Keycloak is not:
LDAP server
Active Directory replacement
HR master data system
full-featured IGA / identity governance suite
WAF / API gateway
replacement for application authorization design
universal SCIM provisioning platform out of the box企业落地时要先拆清楚 4 件事:
Authentication:
who is the user
login flow, MFA, passwordless, federation
Application SSO:
OIDC or SAML integration
session, token, logout, redirect URI
Provisioning:
where users and groups come from
LDAP / AD federation, import, JIT, custom sync, lifecycle offboarding
Authorization:
app roles, groups, claims, resource permissions
usually still needs local app-side authorization model2. Enterprise IdP Architecture#
target architecture#
employees / service admins
-> corporate entry point
-> Keycloak realm
-> identity source:
external LDAP / AD user federation
upstream OIDC / SAML IdP
local emergency admin users
-> policies:
MFA
password policy
brute force protection
token/session lifetime
-> applications:
internal web apps through OIDC
legacy enterprise apps through SAML
APIs through OAuth2 access token
Grafana / GitLab / Argo CD / Jenkins / custom appsdeployment baseline#
production baseline:
Keycloak 运行多个 replicas
external PostgreSQL database
external LDAP / AD if enterprise directory federation is required
stable hostname, HTTPS, correct proxy headers
no embedded dev database
no start-dev in production
realm config managed as code where possible
secrets stored in Vault / K8S Secret / cloud secret manager
logs, metrics, health checks enabled
tested backup / restore / upgrade / rollbacktrust boundary#
Internet / office network
-> WAF / ALB / Ingress / reverse proxy
-> Keycloak HTTPS endpoint
-> PostgreSQL
-> LDAP / AD
-> upstream IdP metadata / JWKS endpoint关键边界:
browser to Keycloak:
HTTPS required
hostname fixed
cookies secure
proxy to Keycloak:
forward headers only from trusted proxy
do not expose internal admin endpoint publicly if split is possible
Keycloak to database:
TLS preferred
DB credential is secret
backup and PITR owned by platform team
Keycloak to LDAP / AD:
LDAPS or StartTLS
bind user least privilege
group search carefully scoped3. Core Concepts#
| Concept | Meaning | 企业方案里的用法 |
|---|---|---|
| Realm | tenant / security domain | 通常 prod 一个主 realm,dev/test 分开 |
| Client | application integration | 每个 app 一个 client,不共用 secret |
| User Federation | LDAP / AD integration | 让 Keycloak 读取企业目录 |
| Identity Provider | upstream OIDC / SAML IdP | Keycloak 作为 broker 接 Okta / Entra ID 等 |
| Authentication Flow | login steps | MFA、conditional flow、fallback |
| Required Action | user must do something | update password, configure OTP |
| Group | user grouping | 映射 team / department / app access |
| Realm Role | realm-wide role | 少量全局权限,不要膨胀 |
| Client Role | app-scoped role | 推荐给业务系统授权使用 |
| Protocol Mapper | token claim mapping | 把 group / role / attribute 放进 token |
| Service Account | machine-to-machine identity | backend job / CI / integration |
| Offline Token | long-lived refresh token | 严格限制,只给必要 integration |
LDAP / AD relationship#
Keycloak 不包含 LDAP server,也不是 AD 的替代品。它可以作为 LDAP / AD client,把企业目录接进 Keycloak,再对下游应用提供 OIDC / OAuth2 / SAML。
LDAP / Active Directory:
stores users, groups, passwords, directory attributes
remains the enterprise directory source
Keycloak:
connects to LDAP / AD through User Federation
validates login against LDAP / AD when configured
maps LDAP users / groups / attributes into Keycloak model
issues OIDC tokens or SAML assertions to applications常见架构:
Active Directory / LDAP
-> Keycloak User Federation
-> OIDC / SAML
-> internal apps / SaaS / APIs关键判断:
use Keycloak local users when:
small internal app
no existing enterprise directory
emergency admin / break-glass account
use LDAP / AD federation when:
company already has employee directory
offboarding must happen from central directory
group membership comes from AD / LDAP
password policy is owned by directory team4. Solution Decision#
Keycloak as primary IdP#
| Use Case | Fit | Notes |
|---|---|---|
| 中小型企业内部应用统一登录 | good | 自管成本可控,OIDC/SAML 覆盖面广 |
| 大量自研业务系统 | good | client / mapper / realm policy 可标准化 |
| 已有 LDAP / AD,但缺现代 OIDC | good | Keycloak 做 federation gateway |
| 多个上游 IdP 需要统一入口 | good | 使用 identity brokering |
| 需要完整 HR lifecycle / access review / SoD | partial | 需要 IGA / HRIS / custom workflow 配合 |
| 只想给 AWS console 做员工 SSO | maybe not | IAM Identity Center 更直接 |
| 面向亿级消费者身份 | depends | 需要专项容量、风控、反欺诈、区域架构 |
realm strategy#
recommended:
dev realm
test realm
prod realm
avoid:
one realm per application
one realm per team without governance
mixing test users and prod users in same realm多 realm 会带来配置复制、客户端重复、运维复杂度。除非有强隔离需求,否则企业员工 IdP 不要随意拆 realm。
protocol strategy#
| Protocol | Use For | Notes |
|---|---|---|
| OIDC Authorization Code + PKCE | modern web / SPA / mobile | 默认优先选择 |
| OAuth2 Client Credentials | service to service | 使用 service account 和 client role |
| SAML 2.0 | legacy SaaS / enterprise software | 注意 metadata、签名、NameID、ACS URL |
| Direct Access Grants | trusted legacy script only | 默认禁用,避免收集用户密码 |
5. Service Configuration#
realm baseline#
realm baseline:
display name and email templates configured
brute force protection enabled
password policy enabled
MFA required for privileged groups
SMTP configured for required actions and reset flows
user profile / required attributes defined
login theme and error page tested
event logging enabledclient baseline#
client baseline:
use confidential client for server-side web app
use public client with PKCE for SPA/mobile
disable implicit flow unless legacy hard requirement exists
use exact redirect URIs, not broad wildcard
keep web origins narrow
rotate client secret
add only required protocol mappers
token audience should match the target APIOIDC web app example:
client_id:
order-web
access type:
confidential
standard flow:
enabled
valid redirect URIs:
https://order.example.com/oauth2/callback
web origins:
https://order.example.com
recommended mappers:
email
preferred_username
groups
client roles for order-apiuser federation baseline#
LDAP / AD federation:
use read-only first unless write-back is explicitly required
use LDAPS / StartTLS
bind DN uses least privilege
search base is scoped to employees / groups only
import users only when needed
sync schedule is documented
group mapper tested with nested group behavior
offboarding test is mandatoryupstream IdP broker baseline#
identity brokering:
define upstream IdP per enterprise source
pin metadata / endpoints where possible
validate signature and issuer
map email / username / groups consistently
decide first-login flow:
auto-link trusted domains
require review for unknown domain
block duplicate email takeover6. Security Best Practices#
admin:
do not use shared admin account
create named admin users
require MFA for admins
split realm-admin from platform-admin
keep emergency break-glass user with strong controls
network:
expose only required frontend hostname
protect admin console by network policy / VPN / separate hostname if possible
trust proxy headers only from controlled proxy
do not run plain HTTP on public edge
tokens:
short access token lifetime
refresh token lifetime aligned with company session policy
offline token only for approved integrations
rotate signing keys with rollout plan
validate issuer, audience, expiry in every app/API
secrets:
client secrets in secret manager
DB password in secret manager
LDAP bind password in secret manager
never commit realm export with real secrets推荐默认值:
| Policy | Recommended Start | Adjust By |
|---|---|---|
| Access token lifespan | 5-15 minutes | API risk, gateway cache, app session model |
| SSO session idle | 8-12 hours | company workday policy |
| SSO session max | 12-24 hours | compliance and UX |
| Admin MFA | required | no exception except break-glass |
| Password policy | length + deny list + history | if password login is enabled |
| Brute force protection | enabled | tune by helpdesk false positive rate |
7. Reliability And Operations#
availability:
run multiple Keycloak replicas
database must be HA
cache / clustering behavior tested under rolling restart
readiness probe prevents broken nodes from receiving traffic
blue/green or canary upgrade for major changes
backup:
PostgreSQL backup is the real backup
realm export is useful for config review and migration, not enough alone
test restore into isolated environment
keep signing keys and secrets in recovery plan
upgrade:
read release notes before version jump
test realm import/export
test login, refresh token, logout, SAML, LDAP sync
keep DB snapshot before upgradeincident checklist:
login failure:
check Keycloak events
check reverse proxy headers and hostname
check redirect URI mismatch
check IdP metadata / certificate / JWKS
check LDAP connectivity and bind auth
token rejected by app:
check issuer
check audience
check clock skew
check signing key rotation
check mapper output
admin console unavailable:
check pod/container status
check database connection
check proxy route
check health endpoint
check recent config or theme deployment8. Monitoring#
must watch:
HTTP 5xx / 4xx rate
login failure rate
request latency p95/p99
JVM memory and GC
DB connection pool usage
PostgreSQL latency / locks / connections
LDAP / upstream IdP connectivity
pod restarts / OOMKilled
certificate expiryalert examples:
| Alert | Suggested Signal | Start Threshold |
|---|---|---|
| KeycloakDown | readiness/health check fails | 2-5 minutes |
| HighLoginFailure | failed login event rate | baseline + sudden spike |
| High5xx | HTTP 5xx ratio | > 1% for 5 minutes |
| SlowLogin | login endpoint p95 latency | > 2s for 10 minutes |
| DBPoolExhaustion | active DB connections / pool max | > 85% for 5 minutes |
| CertExpiring | TLS certificate expiry | < 30 days |
dashboard should include:
traffic:
requests by route / status
login success/failure
token endpoint rate
runtime:
CPU / memory
JVM heap / non-heap
GC pause
thread count
dependency:
DB connections
DB latency
LDAP latency/error
upstream IdP error
business:
active sessions
new users
admin actions9. Hands-on#
local demo only#
docker run --name keycloak-demo --rm \
-p 8080:8080 \
-e KC_BOOTSTRAP_ADMIN_USERNAME=admin \
-e KC_BOOTSTRAP_ADMIN_PASSWORD=change_me_now \
quay.io/keycloak/keycloak:latest \
start-devOpen:
http://localhost:8080/production-style smoke test#
curl -fsS https://sso.example.com/realms/master/.well-known/openid-configuration
curl -fsS https://sso.example.com/health/ready
curl -fsS https://sso.example.com/metricsVerify OIDC discovery output contains:
issuer:
https://sso.example.com/realms/<realm>
authorization_endpoint:
https://sso.example.com/realms/<realm>/protocol/openid-connect/auth
jwks_uri:
https://sso.example.com/realms/<realm>/protocol/openid-connect/certsrollout checklist#
phase 1:
deploy dev realm
integrate one low-risk internal app
verify login / logout / token refresh
phase 2:
connect LDAP / AD or upstream IdP
map groups and claims
enable admin MFA
define client onboarding template
phase 3:
migrate critical internal apps
create monitoring dashboard and alerts
test backup / restore
test IdP outage and DB failover
phase 4:
make Keycloak the default internal app SSO entry
remove local app passwords where possible
run quarterly access review with app owners10. Readiness Criteria#
security ready:
HTTPS and hostname are correct
admin MFA enforced
client secrets managed outside Git
redirect URIs reviewed
token validation standard documented for apps
operation ready:
HA deployment tested
DB backup restore tested
monitoring and alerts enabled
upgrade rehearsal done
incident runbook exists
governance ready:
owner for realm changes
owner for client onboarding
owner for LDAP / IdP mapping
offboarding test completed
break-glass process approved