跳到主内容

添加 Keycloak 作为 SAML 提供商

本指南说明如何让 Keycloak realm 的用户通过 SAML 登录到 Casdoor。Keycloak 是一个支持 SAML 和 OpenID Connect 的开源 IdP,并且可以代理 LDAP 和其他身份提供商。


学习成果​

  • 在 Keycloak 中为 Casdoor 创建一个 SAML 客户端。
  • 在 Casdoor 中将 Keycloak 添加为 SAML 提供商。
  • 如果 Keycloak 需要,对认证请求进行签名。

所需条件​

  • Keycloak 服务器的管理员访问权限
  • Casdoor admin console 的管理员访问权限

以下示例假设了这些地址。请根据你的部署情况进行调整。

ComponentAddress
Casdoor UIhttp://localhost:7001
Casdoor APIhttp://localhost:8000
Keycloakhttp://localhost:8080/auth
SP ACS URL 和实体 IDhttp://localhost:8000/api/acs

准备 Realm​

使用默认 realm 或创建一个。

Add realm in Keycloak

Realm settings in Keycloak

在 Keycloak 中创建 SAML 客户端​

有关所有客户端设置,请参阅 Keycloak 文档中的 SAML clients。

  1. 前往 Clients 并点击 Create。填写 Add Client 页面:

    FieldValue
    Client IDhttp://localhost:8000/api/acs. This is the SP entity ID of Casdoor
    Client Protocolsaml
    Client SAML Endpointhttp://localhost:8000/api/acs,即 Keycloak 发送 SAML 请求和响应的地址

    Add Client page

  2. 单击 Save(保存)。 The Settings tab opens.

  3. 设置以下值并保存:

    SettingValue
    NameA friendly name, such as Casdoor
    EnabledOn
    Include Authn StatementOn
    Sign DocumentsOn
    Sign AssertionsOff
    Encrypt AssertionsOff
    Client Signature RequiredOff. See Sign the authentication request
    Force Name ID FormatOn
    Name ID Formatusername
    Valid Redirect URIshttp://localhost:8000/api/acs
    Master SAML Processing URLhttp://localhost:8000/api/acs
    Assertion Consumer Service POST Binding URLhttp://localhost:8000/api/acs, under Fine Grain SAML Endpoint Configuration
    Assertion Consumer Service Redirect Binding URLhttp://localhost:8000/api/acs

    Settings of the client

    /api/acs 端点仅接受 POST 请求,因此 Keycloak 必须使用 POST binding 发送响应。

  4. 前往 Installation 选项卡并获取元数据:

    • 在 Keycloak 5.0.0 及更早版本中,选择格式 SAML Metadata IDPSSODescriptor 并复制元数据。
    • 在 Keycloak 6.0.0 及更高版本中,选择 Mod Auth Mellon files,点击 Download,解压文件,并复制 idp-metadata.xml 的内容。

    Installation tab

    Metadata of the client

在 Casdoor 中添加提供商​

  1. 在 Casdoor admin console 中,前往 Identity > Providers 并添加一个提供商。

  2. 将 Category 设置为 SAML,将 Type 设置为 Keycloak。

  3. 将元数据粘贴到 Metadata 中,然后点击 Parse。Casdoor 会自动填充 Endpoint、IdP 和 Issuer URL。

    Keycloak provider in Casdoor

  4. 保存提供商.

  5. 打开应用的编辑页面,在 Providers 选项卡中添加提供商,然后保存。

    Keycloak provider in the application

对认证请求进行签名​

为了让 Keycloak 验证 Casdoor 的请求:

  1. 在 Keycloak 中,为该客户端启用 Client Signature Required。
  2. 在 Casdoor 管理控制台中,前往 Identity > Certs,打开 cert-built-in,然后点击 Download certificate。Casdoor 使用 admin 组织的此证书对认证请求进行签名,其私钥存储在数据库中。
  3. 在 Keycloak 中,前往 Keys > Import,选择归档格式 Certificate PEM,并上传证书。
  4. 在 Casdoor 中,在提供商上启用 Sign request。

如果 cert-built-in 不存在,登录将失败并显示错误 the cert: admin/cert-built-in is not found。如果您替换了 cert-built-in 的密钥对,请在 Keycloak 中重新导入新证书。参见 Certificates。

验证结果​

打开应用的登录页面并点击 Keycloak 按钮。在 Keycloak 登录后,您也将登录到 Casdoor。

Recording of the sign-in through Keycloak

另请参阅​