Keycloak


本文缩写(英文全称与中文含义)
缩写 英文全称/名称 中文含义
ACS Assertion Consumer Service SAML 断言消费服务端点
AD Active Directory 微软活动目录
ALB Application Load Balancer 应用负载均衡器
API Application Programming Interface 应用程序编程接口
AWS Amazon Web Services 亚马逊云服务
CD Continuous Delivery / Continuous Deployment 持续交付/持续部署;是否自动上线取决于流程
CI Continuous Integration 持续集成
CPU Central Processing Unit 中央处理器
DB Database 数据库
DN Distinguished Name 目录条目的唯一名称
GC Garbage Collection 垃圾回收
HA High Availability 高可用
HR Human Resources 人力资源
HRIS Human Resources Information System 人力资源信息系统
HTTP Hypertext Transfer Protocol 超文本传输协议
HTTPS Hypertext Transfer Protocol Secure 使用 TLS 加密的 HTTP
IAM Identity and Access Management 身份与访问管理
ID Identifier 标识符
IGA Identity Governance and Administration 身份治理与管理
JIT Just-In-Time 即时处理;身份系统中常指首次登录时即时创建用户
JVM Java Virtual Machine Java 虚拟机
JWKS JSON Web Key Set JSON Web 密钥集,常用于验证令牌签名
K8S Kubernetes 容器编排平台;8 表示 K 与 s 之间的八个字母
LDAP Lightweight Directory Access Protocol 轻量级目录访问协议
LDAPS LDAP over TLS 通过 TLS 保护的 LDAP
MFA Multi-Factor Authentication 多因素认证
OIDC OpenID Connect 基于 OAuth 2.0 的身份认证协议
OTP One-Time Password 一次性密码
PITR Point-In-Time Recovery 时间点恢复
PKCE Proof Key for Code Exchange OAuth 授权码交换证明密钥机制
SaaS Software as a Service 软件即服务
SAML Security Assertion Markup Language 安全断言标记语言,用于身份联合
SCIM System for Cross-domain Identity Management 跨域身份管理协议,用于用户/组同步
SMTP Simple Mail Transfer Protocol 简单邮件传输协议
SoD Separation of Duties 职责分离
SPA Single-Page Application 单页应用
SSO Single Sign-On 单点登录
TLS Transport Layer Security 传输层安全协议
URI Uniform Resource Identifier 统一资源标识符
URL Uniform Resource Locator 统一资源定位符,通常指访问地址
UX User Experience 用户体验
VPN Virtual Private Network 虚拟专用网络
WAF Web Application Firewall Web 应用防火墙
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-config

1. 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 model

2. 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 apps

deployment 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 / rollback

trust 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 scoped

3. 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 team

4. 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 enabled

client 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 API

OIDC 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-api

user 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 mandatory

upstream 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 takeover

6. 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 upgrade

incident 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 deployment

8. 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 expiry

alert 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 actions

9. 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-dev

Open:

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/metrics

Verify 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/certs

rollout 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 owners

10. 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

搜索文档

输入关键词,搜索所有文档。

↑ ↓ 选择 · Enter 打开 · Esc 关闭