跳到主内容

Casdoor 作为开源 SAML 2.0 身份提供商 (IdP)

Casdoor 是一个 SAML 2.0 身份提供商 (IdP)。本页解释了在服务提供商 (SP) 和 Casdoor 中分别配置哪些内容,以及 SAML 响应携带哪些用户数据。有关特定服务提供商的分步指南,请参阅本节的其他页面。

配置服务提供商​

服务提供商通常请求三个值:单点登录 URL、发行者(Issuer)和 IdP 的公钥证书。大多数服务提供商通过 URL 或上传的文件,从 IdP 的 SAML 元数据中读取这三个值。

Casdoor 应用的元数据 URL 为:

<casdoor-host>/api/saml/metadata?application=admin/<application-name>

例如,对于位于 https://door.casdoor.com 的 Casdoor 和应用 app-built-in:

https://door.casdoor.com/api/saml/metadata?application=admin/app-built-in

要在 Casdoor 管理控制台中获取该 URL,请打开应用的编辑页面,转到 SAML 选项卡,然后单击 Copy SAML metadata URL。要将元数据下载为 XML 文件,请在浏览器中打开该 URL。

SAML metadata of the application

配置 Casdoor 应用​

在应用的编辑页面上,设置以下两个字段:

Field值
Redirect URLsThe identifier of the service provider, which the SP calls the audience or the entity ID. Enter exactly the same value as in the SP
SAML reply URLSP 的断言消费者服务 (ACS) URL,用于接收并验证 SAML 响应。留空则使用重定向绑定

Redirect URLs field with the entity ID

SAML reply URL field

响应绑定​

Casdoor 可以通过 HTTP POST 请求或 HTTP GET 请求发送 SAMLResponse。请选择您的服务提供商支持的方式:

SAML reply URLBindingWhere Casdoor sends the response
SetPOSTTo the reply URL. The reply URL overrides the AssertionConsumerServiceURL of the SAMLRequest
EmptyGETTo the AssertionConsumerServiceURL that Casdoor reads from the SAMLRequest
备注

当 Casdoor 本身在外部 SAML IdP(如 Azure AD)处为用户登录时,外部 IdP 会将其 SAML 响应发布到 Casdoor 的 /api/acs 端点。该端点接受跨域 POST 请求,以便来自其他域的 IdP 可以发送响应。

从 Casdoor 启动登录(IdP 发起的单点登录)​

在 IdP 发起的单点登录中,用户从 Casdoor 开始,而不是从服务提供商开始。Casdoor 向 SP 发送一个没有对应 AuthnRequest 的 SAML 响应。这适用于门户链接和书签。

  1. 在应用的 SAML 选项卡上,将 SAML reply URL 设置为 SP 的 ACS URL。如果不设置,登录将失败并报错 the SAML reply URL should not be empty for IdP-initiated SSO。

  2. 确保 Redirect URLs 的第一项是 SP 的实体 ID。Casdoor 将其用作断言的受众(Audience)。

  3. 保存应用。SAML 选项卡随后将显示 IdP-initiated SSO URL:

    <casdoor-host>/login/saml/authorize/admin/<application-name>
  4. 单击 Copy IdP-initiated SSO URL,并将该 URL 提供给您的用户。

打开该 URL 的用户将登录到 Casdoor,然后 Casdoor 使用 HTTP-POST 绑定将 SAML 响应发布到回复 URL。由于之前没有请求,响应中没有 InResponseTo 属性。要向 SP 传递 RelayState,请将其作为查询参数添加到 URL 中,例如 ?RelayState=/dashboard。

让用户从 SP 注销(单点登出)​

Casdoor 支持双向 SAML 单点登出 (SLO)。要启用此功能,请在应用的 SAML 选项卡上将 SAML single logout URL 设置为 SP 的 SingleLogoutService URL。

应用的元数据在以下位置声明了 Casdoor 的 SingleLogoutService,包含 HTTP-Redirect 和 HTTP-POST 绑定:

<casdoor-backend-host>/api/saml/logout/admin/<application-name>

每个断言在其 AuthnStatement 中都携带一个 SessionIndex,用于标识此次登录的 Casdoor 会话。

SP 发起的登出​

当用户在 SP 处注销时,SP 会通过 GET 或 POST 方法,在 SAMLRequest 参数以及可选的 RelayState 参数中,向 Casdoor 的 SingleLogoutService 发送 LogoutRequest:

  1. Casdoor 检查该请求。其 Issuer 必须存在于 Redirect URLs 中,必须包含 NameID,且应用必须设置了 SAML single logout URL。
  2. Casdoor 结束由请求中的 SessionIndex 值指定的 Casdoor 会话。如果没有 SessionIndex,它仅结束发送请求的浏览器会话,并且仅当 NameID 属于该用户时才这样做。
  3. Casdoor 会将用户从这些会话中的其他应用注销,使用 OIDC 后台通道登出和 SAML 登出请求。
  4. Casdoor 通过请求所使用的绑定方式回复签名的 LogoutResponse:对于 GET,重定向到 SAML single logout URL;对于 POST,发送一个表单让浏览器发布到该 URL。

IdP 发起的登出​

当用户通过 /api/logout 或 /api/sso-logout 从 Casdoor 注销时,Casdoor 会向用户在已结束的会话中登录过的每个 SAML 应用的 SAML single logout URL 发送签名的 LogoutRequest。当 Casdoor 因其他原因结束会话时也会发生同样的情况,例如禁止用户登录,或新登录超出会话限制。Casdoor 像 OIDC 后台通道登出 一样从服务器端发布这些请求,而不是通过浏览器。当 SP 向其同一个 SingleLogoutService 端点发送 LogoutResponse 时,Casdoor 会检查其 Issuer 是否在 Redirect URLs 中,以及状态是否为 Success。

响应中的用户配置文件​

默认情况下,SAMLResponse 携带用户的三个属性:

XML属性名称用户字段
邮箱电子邮件
DisplayNamedisplayName
Namename

如果服务提供商只需要 NameID 而不需要属性,请在应用上开启 Disable SAML attributes。Casdoor 随后会在响应中省略属性。这避免了严格验证响应的服务提供商出现的 XML 命名空间问题。

添加 SAML 属性​

如果服务提供商需要其他属性,请将它们添加到应用的 SAML attributes 表中。值可以包含以下变量:$user.owner、$user.name、$user.displayName、$user.email、$user.id、$user.phone、$user.roles、$user.permissions 和 $user.groups。

例如,以下两行:

Name名称格式Value
https://www.aliyun.com/SAML-Role/Attributes/RoleSessionName未指定$user.name
https://www.aliyun.com/SAML-Role/Attributes/Role未指定acs:ram::1879818006829152:role/$user.roles,acs:ram::1879818006829152:saml-provider/testa

将在响应中生成这些属性:

<saml:Attribute Name="https://www.aliyun.com/SAML-Role/Attributes/RoleSessionName" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified">
<saml:AttributeValue xsi:type="xs:string">admi122n@outlook.com</saml:AttributeValue>
</saml:Attribute>
<saml:Attribute Name="https://www.aliyun.com/SAML-Role/Attributes/Role" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified">
<saml:AttributeValue xsi:type="xs:string"> acs:ram::1879818006829152:role/role1,acs:ram::1879818006829152:saml-provider/testa</saml:AttributeValue>
<saml:AttributeValue xsi:type="xs:string"> acs:ram::1879818006829152:role/role2,acs:ram::1879818006829152:saml-provider/testa</saml:AttributeValue>
</saml:Attribute>

控制断言签名​

Casdoor 始终对 SAML 响应进行签名。要对响应内部的断言也进行签名,请在应用上开启 Enable SAML assertion signature。此选项默认关闭。

版本 2.81.0 到 2.247.x 始终也对断言进行签名。某些服务提供商(如 Sentry)拒绝带有签名断言的响应,因此自版本 2.248.0 起,除非开启该选项,否则 Casdoor 仅对响应信封进行签名。签名的响应也能保证断言的真实性。

使用 Go 服务提供商进行测试​

gosaml2 是 Go 语言中面向服务提供商的 SAML 2.0 实现。以下程序使用它来测试 Casdoor 作为 IdP。

该示例假设 Casdoor 运行在 http://localhost:7001/,并使用组织 built-in 的应用 app-built-in。

  1. 将 http://localhost:6900/acs/example 和 http://localhost:6900/saml/acs/example 添加到 app-built-in 的 Redirect URLs 中。

  2. 运行程序:

    import (
    "crypto/x509"
    "fmt"
    "net/http"

    "io/ioutil"

    "encoding/base64"
    "encoding/xml"

    saml2 "github.com/russellhaering/gosaml2"
    "github.com/russellhaering/gosaml2/types"
    dsig "github.com/russellhaering/goxmldsig"
    )

    func main() {
    res, err := http.Get("http://localhost:7001/api/saml/metadata?application=admin/app-built-in")
    if err != nil {
    panic(err)
    }

    rawMetadata, err := ioutil.ReadAll(res.Body)
    if err != nil {
    panic(err)
    }

    metadata := &types.EntityDescriptor{}
    err = xml.Unmarshal(rawMetadata, metadata)
    if err != nil {
    panic(err)
    }

    certStore := dsig.MemoryX509CertificateStore{
    Roots: []*x509.Certificate{},
    }

    for _, kd := range metadata.IDPSSODescriptor.KeyDescriptors {
    for idx, xcert := range kd.KeyInfo.X509Data.X509Certificates {
    if xcert.Data == "" {
    panic(fmt.Errorf("metadata certificate(%d) must not be empty", idx))
    }
    certData, err := base64.StdEncoding.DecodeString(xcert.Data)
    if err != nil {
    panic(err)
    }

    idpCert, err := x509.ParseCertificate(certData)
    if err != nil {
    panic(err)
    }

    certStore.Roots = append(certStore.Roots, idpCert)
    }
    }

    randomKeyStore := dsig.RandomKeyStoreForTest()

    sp := &saml2.SAMLServiceProvider{
    IdentityProviderSSOURL: metadata.IDPSSODescriptor.SingleSignOnServices[0].Location,
    IdentityProviderIssuer: metadata.EntityID,
    ServiceProviderIssuer: "http://localhost:6900/acs/example",
    AssertionConsumerServiceURL: "http://localhost:6900/v1/_saml_callback",
    SignAuthnRequests: true,
    AudienceURI: "http://localhost:6900/saml/acs/example",
    IDPCertificateStore: &certStore,
    SPKeyStore: randomKeyStore,
    }

    http.HandleFunc("/v1/_saml_callback", func(rw http.ResponseWriter, req *http.Request) {
    err := req.ParseForm()
    if err != nil {
    rw.WriteHeader(http.StatusBadRequest)
    return
    }
    samlReponse := req.URL.Query().Get("SAMLResponse")
    assertionInfo, err := sp.RetrieveAssertionInfo(samlReponse)
    if err != nil {
    fmt.Println(err)
    rw.WriteHeader(http.StatusForbidden)
    return
    }
    fmt.Println(assertionInfo)
    if assertionInfo.WarningInfo.InvalidTime {
    fmt.Println("here12:", assertionInfo.WarningInfo.InvalidTime)
    rw.WriteHeader(http.StatusForbidden)
    return
    }

    if assertionInfo.WarningInfo.NotInAudience {
    fmt.Println(assertionInfo)
    fmt.Println("here13:", assertionInfo.WarningInfo.NotInAudience)
    rw.WriteHeader(http.StatusForbidden)
    return
    }

    fmt.Fprintf(rw, "NameID: %s\n", assertionInfo.NameID)

    fmt.Fprintf(rw, "Assertions:\n")

    for key, val := range assertionInfo.Values {
    fmt.Fprintf(rw, " %s: %+v\n", key, val)
    }
    fmt.Println(assertionInfo.Values.Get("FirstName"))
    fmt.Fprintf(rw, "\n")

    fmt.Fprintf(rw, "Warnings:\n")
    fmt.Fprintf(rw, "%+v\n", assertionInfo.WarningInfo)
    })

    println("Visit this URL To Authenticate:")
    authURL, err := sp.BuildAuthURL("")
    if err != nil {
    panic(err)
    }

    println(authURL)

    println("Supply:")
    fmt.Printf(" SP ACS URL : %s\n", sp.AssertionConsumerServiceURL)

    err = http.ListenAndServe(":6900", nil)
    if err != nil {
    panic(err)
    }
    }

    控制台显示:

    Visit this URL To Authenticate:
    http://localhost:7001/login/saml/authorize/admin/app-built-in?SAMLRequest=lFVbk6K8Fv0rFvNo2QR...
    Supply:
    SP ACS URL : http://localhost:6900/v1/_saml_callback
  3. 打开 URL。将出现 Casdoor 登录页面。

    Casdoor sign-in page

  4. 登录。程序将打印 SAML 响应。

    SAML response in the console

另请参阅​