karolornoch/php-saml

PHP SAML 工具包

4.1.0 2022-07-15 20:44 UTC

This package is auto-updated.

Last update: 2024-09-13 14:18:17 UTC


README

php-saml package Coverage Status Packagist Dependency Version (specify version) License Packagist Downloads Packagist Downloads

使用此库将 SAML 支持添加到您的 PHP 软件。

3.X 分支与 PHP > 7.1 兼容,因此如果您使用该 PHP 版本,请使用它而不是 2.X 或 master 分支

警告

版本 2.18.0 引入了 'rejectUnsolicitedResponsesWithInResponseTo' 设置参数,默认禁用,允许使未经请求的 SAMLResponse 失效。此版本还将拒绝 SAMLResponse,如果 requestId 提供给验证器但 SAMLResponse 不包含 InResponseTo 属性。此外,还有一个额外的设置参数 'destinationStrictlyMatches',默认禁用,将强制 Destination URL 必须严格匹配处理 SAMLResponse 的地址。

版本 2.17.1 将 xmlseclibs 更新到 3.0.4 (CVE-2019-3465),但 php-saml 没有直接受到影响,因为它实现了额外的检查,防止利用该漏洞。

版本 2.17.0 默认启用严格模式

将 php-saml 更新到 2.15.0,此版本包含与 XEE 攻击相关的安全补丁

php-saml 未受 201803-01 影响

将 php-saml 更新到 2.10.4,此版本包含与 LogoutRequests/LogoutResponses 上的签名验证 相关的安全补丁

将 php-saml 更新到 2.10.0,此版本包含包含额外验证的安全补丁,可防止签名包装攻击。 CVE-2016-1000253

php-saml < v2.10.0 存在漏洞,允许签名包装!

安全指南

如果您认为您在此工具包中发现了一个安全漏洞,请通过邮件向维护者报告: sixto.martin.garcia+security@gmail.com

为什么要在我的软件中添加 SAML 支持?

SAML 是一种基于 XML 的用于网页浏览器单点登录的标准,由 OASIS 安全服务技术委员会定义。该标准自 2002 年以来一直存在,但最近由于其优势而变得越来越流行。

  • 可用性 - 从门户网站或内部网络一键访问,深度链接,消除密码和自动续订会话,使用户的生活更轻松。
  • 安全性 - 基于强大的数字签名进行身份验证和完整性,SAML 是一种安全的单点登录协议,全球最大、最注重安全的企业都依赖它。
  • 速度 - SAML 很快。只需一次浏览器重定向即可安全地将用户登录到应用程序。
  • 钓鱼预防 - 如果您没有应用程序的密码,您就不会被诱骗在假登录页面上输入它。
  • IT 友好 - SAML 简化了 IT 的工作,因为它集中了身份验证,提供了更大的可见性,并使目录集成更容易。
  • 机会 - B2B 云供应商应支持 SAML,以促进其产品集成。

一般描述

SAML PHP 工具包让您在 PHP 应用程序上构建 SP(服务提供者),并将其连接到任何 IdP(身份提供者)。

支持

  • SSO 和 SLO(SP-Initiated 和 IdP-Initiated)。
  • 断言和 nameId 加密。
  • 断言签名。
  • 消息签名:AuthNRequest、LogoutRequest、LogoutResponses。
  • 启用断言消费者服务端点。
  • 启用单点退出服务端点。
  • 发布 SP 元数据(可以签名)。

主要功能

  • saml2int - 实现SAML 2.0 Web浏览器SSO配置文件。
  • 无会话 - 忘掉那些SP和最终应用程序之间的常见冲突,工具包将委托最终应用程序中的会话。
  • 易于使用 - 程序员将能够进行高级和低级编程,提供2个易于使用的API。
  • 已测试 - 已彻底测试。
  • 流行 - 客户使用它。许多PHP SAML插件使用它。

使用本指南在OneLogin中集成PHP工具包:https://developers.onelogin.com/page/saml-toolkit-for-php

安装

依赖项

  • php >= 5.3.3 以及一些核心扩展,如 php-xmlphp-datephp-zlib
  • openssl。安装openssl库。它处理x509证书。
  • mcrypt。如果您打算处理加密数据(nameIDassertions),请安装该库及其php驱动程序。
  • gettext。安装该库及其php驱动程序。它处理翻译。
  • curl。如果您打算使用IdP元数据解析器,请安装该库及其php驱动程序。

由于 PHP 5.3 已正式停止支持,我们建议您使用较新的PHP版本。

代码

选项1. 从github克隆仓库

git clone git@github.com:onelogin/php-saml.git

选项2. 从github下载

工具包托管在github上。您可以从中下载

将库的核心复制到php应用程序中。(每个应用程序都有自己的结构,因此请花时间找到最佳位置的PHP SAML工具包)。参见“添加SAML支持到我的应用程序指南”以了解详情。

请注意,压缩文件仅包含主要文件。如果您打算使用演示,请使用选项1。

选项3. Composer

工具包支持 composer。您可以在 https://packagist.org.cn/packages/onelogin/php-saml 找到 onelogin/php-saml 包。

要将saml工具包导入到当前的php项目中,请执行以下操作

composer require onelogin/php-saml

安装完成后,您将在 vendor/ 文件夹中找到一个名为 onelogin 的新文件夹,其中包含 php-saml。请确保您正在包含由composer提供的自动加载器。它可以在 vendor/autoload.php 中找到。

重要 在此选项中,x509证书必须存储在 vendor/onelogin/php-saml/certs 中,设置文件存储在 vendor/onelogin/php-saml 中。

当使用 composer update 或类似命令更新包时,您的设置可能会被删除。因此,强烈建议您不是使用设置文件,而是直接将设置作为数组传递给构造函数(在本文档的后面解释)。如果您不使用这种方法,当使用 composer update 或类似命令更新包时,您的设置可能会被删除。

兼容性

此2.0版本有一个新的库。工具包仍然兼容。

您用于添加SAML支持的旧代码将继续工作,只需进行一些小的更改。您只需要加载 lib/Saml 文件夹中的文件。(注意,compatibility.php 文件就是这样做的)。

旧-demo文件夹包含使用旧版本工具包(v.1)的旧应用程序的代码。查看一下。

有时旧代码中类的名称可能略有不同,如果这种情况适用于您,则必须将它们更改为 OneLogin_Saml_SettingsOneLogin_Saml_ResponseOneLogin_Saml_AuthRequestOneLogin_Saml_Metadata

我们建议您将旧代码迁移到新版本,以便使用新库Saml2带来的新功能。

命名空间

如果您正在使用包含命名空间的框架(如Symfony)与库一起使用,请记住,调用类必须通过在开头添加反斜杠(\)来完成,例如,要使用静态方法 getSelfURLNoQuery,请使用

\OneLogin_Saml2_Utils::getSelfURLNoQuery()

安全警告

在生产环境中,必须将 strict 参数设置为 "true",并且必须在 security 下的 signatureAlgorithmdigestAlgorithm 设置为除 SHA1 之外的内容(请参阅 https://shattered.io/)。否则,您的环境将不安全,并容易受到攻击。

在生产环境中,我们还强烈建议在设置中注册IdP证书而不是使用指纹方法。指纹是一个哈希值,因此最终容易受到碰撞攻击,这可能导致签名验证绕过。其他SAML工具集已弃用该机制,我们保留它以保持兼容性,并用于测试环境。

避免Open Redirect攻击

一些实现使用RelayState参数作为控制SSO和SLO成功时的流的方式。因此,基本上用户将被重定向到RelayState的值。

如果您正在使用HTTP-Redirect绑定上的签名验证,则将保护RelayState值的完整性,否则,在HTTP-POST绑定中,您不能信任RelayState,因此在执行验证之前,您需要验证其值是否属于受信任和预期的URL。

有关Open Redirect的更多信息,请参阅 CWE-601

避免Reply攻击

Reply攻击基本上是尝试重用截获的有效SAML消息来模仿SAML操作(SSO或SLO)。

SAML消息具有有限的有效期(NotBefore、NotOnOrAfter),这使得这种攻击变得更加困难,但它们仍然可能发生。

为了避免它们,SP可以保留已验证和处理的SAML消息或断言ID的列表。这些值只需要存储SAML消息生命周期的时长,所以我们不需要存储所有已处理的消息/断言ID,但最 recent ones。

OneLogin_Saml2_Auth类包含getLastRequestIDgetLastMessageIdgetLastAssertionId 方法来检索ID

检查当前消息/断言的ID是否不在已处理的列表中,将防止Reply攻击。

入门

了解工具包

新的OneLogin SAML工具包包含不同的文件夹(certsendpointsextliblibdemo等)和一些文件。

让我们先描述一下文件夹

certs/

SAML需要x509证书来签名和加密诸如NameIDMessageAssertionMetadata之类的元素。

如果我们的环境需要签名或加密支持,则此文件夹可能包含SP将使用的x509证书和私钥

  • sp.crt - SP的公共证书
  • sp.key - SP的私钥

或者我们也可以在设置文件中提供这些数据,在 $settings['sp']['x509cert']$settings['sp']['privateKey'] 中。

有时我们需要在SP发布的元数据上签名,在这种情况下,我们可以使用之前提到的x509证书,或者使用新的x509证书:metadata.crtmetadata.key

如果您正在进行密钥轮换过程,并且想在服务提供商元数据上发布该x509证书,请使用sp_new.crt

extlib/

此文件夹包含工具包使用的第三方库。目前只使用xmlseclibs(作者Robert Richards,BSD许可),该库处理xml元素的签名和加密。

lib/

此文件夹包含工具包的核心,即库

  • Saml文件夹包含工具包v.1的修改版本,允许旧代码继续工作。(此库提供以保持向后兼容性)。
  • Saml2文件夹包含在后续章节中描述的新版本类和方法。

doc/

此文件夹包含工具包的API文档。

endpoints/

工具包有三个端点

  • metadata.php - SP元数据发布的位置。
  • acs.php - 断言消费者服务。处理SAML响应。
  • sls.php - 单一登出服务。处理登出请求和登出响应。

您可以使用工具包提供的文件,或者在添加SAML支持到您的应用程序时创建自己的端点文件。请注意,这些端点文件使用工具包基本文件夹的设置文件。

locale/

Locale文件夹包含一些翻译:en_USes_ES作为概念证明。目前没有翻译,但我们将最终本地化消息并支持多种语言。

其他重要文件

  • settings_example.php - 创建包含工具包基本配置信息的settings.php文件的模板。
  • advanced_settings_example.php - 创建包含与安全、联系人以及与SP关联的组织的额外配置信息的advanced_settings.php文件的模板。
  • _toolkit_loader.php - 此文件加载工具包库(SAML2库)。
  • compatibility - 导入此文件以使您的旧代码与新工具包兼容(加载SAML库)。

杂项

  • tests/ - 包含工具包的单元测试。
  • demo1/ - 包含一个具有SAML支持的简单PHP应用程序的示例。阅读其中的Readme.txt以获取更多信息。
  • demo2/ - 包含另一个示例。
  • demo-old/ - 包含一个使用较旧版本工具包代码的示例,以演示向后兼容性。

工作原理

设置

首先,我们需要配置工具包。SP的信息、IdP的信息,以及在某些情况下,配置高级安全问题,如签名和加密。

提供设置信息有两种方式

  • 使用位于工具包基本文件夹中的settings.php文件。
  • 使用包含设置数据的数组,并将其直接提供给类的构造函数。

有一个模板文件settings_example.php,您可以复制此文件,重命名并编辑它。

<?php

$settings = array (
    // If 'strict' is True, then the PHP Toolkit will reject unsigned
    // or unencrypted messages if it expects them to be signed or encrypted.
    // Also it will reject the messages if the SAML standard is not strictly
    // followed: Destination, NameId, Conditions ... are validated too.
    'strict' => true,

    // Enable debug mode (to print errors).
    'debug' => false,

    // Set a BaseURL to be used instead of try to guess
    // the BaseURL of the view that process the SAML Message.
    // Ex http://sp.example.com/
    //    http://example.com/sp/
    'baseurl' => null,

    // Service Provider Data that we are deploying.
    'sp' => array (
        // Identifier of the SP entity  (must be a URI)
        'entityId' => '',
        // Specifies info about where and how the <AuthnResponse> message MUST be
        // returned to the requester, in this case our SP.
        'assertionConsumerService' => array (
            // URL Location where the <Response> from the IdP will be returned
            'url' => '',
            // SAML protocol binding to be used when returning the <Response>
            // message. SAML Toolkit supports this endpoint for the
            // HTTP-POST binding only.
            'binding' => 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST',
        ),
        // If you need to specify requested attributes, set a
        // attributeConsumingService. nameFormat, attributeValue and
        // friendlyName can be omitted
        "attributeConsumingService"=> array(
                "serviceName" => "SP test",
                "serviceDescription" => "Test Service",
                "requestedAttributes" => array(
                    array(
                        "name" => "",
                        "isRequired" => false,
                        "nameFormat" => "",
                        "friendlyName" => "",
                        "attributeValue" => array()
                    )
                )
        ),
        // Specifies info about where and how the <Logout Response> message MUST be
        // returned to the requester, in this case our SP.
        'singleLogoutService' => array (
            // URL Location where the <Response> from the IdP will be returned
            'url' => '',
            // SAML protocol binding to be used when returning the <Response>
            // message. SAML Toolkit supports the HTTP-Redirect binding
            // only for this endpoint.
            'binding' => 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect',
        ),
        // Specifies the constraints on the name identifier to be used to
        // represent the requested subject.
        // Take a look on lib/Saml2/Constants.php to see the NameIdFormat supported.
        'NameIDFormat' => 'urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress',
        // Usually x509cert and privateKey of the SP are provided by files placed at
        // the certs folder. But we can also provide them with the following parameters
        'x509cert' => '',
        'privateKey' => '',

        /*
         * Key rollover
         * If you plan to update the SP x509cert and privateKey
         * you can define here the new x509cert and it will be
         * published on the SP metadata so Identity Providers can
         * read them and get ready for rollover.
         */
        // 'x509certNew' => '',
    ),

    // Identity Provider Data that we want connected with our SP.
    'idp' => array (
        // Identifier of the IdP entity  (must be a URI)
        'entityId' => '',
        // SSO endpoint info of the IdP. (Authentication Request protocol)
        'singleSignOnService' => array (
            // URL Target of the IdP where the Authentication Request Message
            // will be sent.
            'url' => '',
            // SAML protocol binding to be used when returning the <Response>
            // message. SAML Toolkit supports the HTTP-Redirect binding
            // only for this endpoint.
            'binding' => 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect',
        ),
        // SLO endpoint info of the IdP.
        'singleLogoutService' => array (
            // URL Location of the IdP where SLO Request will be sent.
            'url' => '',
            // URL location of the IdP where the SP will send the SLO Response (ResponseLocation)
            // if not set, url for the SLO Request will be used
            'responseUrl' => '',
            // SAML protocol binding to be used when returning the <Response>
            // message. SAML Toolkit supports the HTTP-Redirect binding
            // only for this endpoint.
            'binding' => 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect',
        ),
        // Public x509 certificate of the IdP
        'x509cert' => '',
        /*
         *  Instead of use the whole x509cert you can use a fingerprint in order to
         *  validate a SAMLResponse, but we don't recommend to use that
         *  method on production since is exploitable by a collision attack.
         *  (openssl x509 -noout -fingerprint -in "idp.crt" to generate it,
         *   or add for example the -sha256 , -sha384 or -sha512 parameter)
         *
         *  If a fingerprint is provided, then the certFingerprintAlgorithm is required in order to
         *  let the toolkit know which algorithm was used. Possible values: sha1, sha256, sha384 or sha512
         *  'sha1' is the default value.
         *
         *  Notice that if you want to validate any SAML Message sent by the HTTP-Redirect binding, you
         *  will need to provide the whole x509cert.
         */
        // 'certFingerprint' => '',
        // 'certFingerprintAlgorithm' => 'sha1',

        /* In some scenarios the IdP uses different certificates for
         * signing/encryption, or is under key rollover phase and
         * more than one certificate is published on IdP metadata.
         * In order to handle that the toolkit offers that parameter.
         * (when used, 'x509cert' and 'certFingerprint' values are
         * ignored).
         */
        // 'x509certMulti' => array(
        //      'signing' => array(
        //          0 => '<cert1-string>',
        //      ),
        //      'encryption' => array(
        //          0 => '<cert2-string>',
        //      )
        // ),
    ),
);

除了必需的设置数据(IdP、SP)之外,还可以定义额外信息。与基本信息的模板存在一样,在工具包基本文件夹中还有一个名为advanced_settings_example.php的模板,您可以复制并重命名为advanced_settings.php

<?php

$advancedSettings = array (

    // Compression settings
    'compress' => array (
        'requests' => true,
        'responses' => true
    ),
    // Security settings
    'security' => array (

        /** signatures and encryptions offered */

        // Indicates that the nameID of the <samlp:logoutRequest> sent by this SP
        // will be encrypted.
        'nameIdEncrypted' => false,

        // Indicates whether the <samlp:AuthnRequest> messages sent by this SP
        // will be signed.  [Metadata of the SP will offer this info]
        'authnRequestsSigned' => false,

        // Indicates whether the <samlp:logoutRequest> messages sent by this SP
        // will be signed.
        'logoutRequestSigned' => false,

        // Indicates whether the <samlp:logoutResponse> messages sent by this SP
        // will be signed.
        'logoutResponseSigned' => false,

        /* Sign the Metadata
         False || True (use sp certs) || array (
                                                    keyFileName => 'metadata.key',
                                                    certFileName => 'metadata.crt'
                                               )
                                      || array (
                                                    'x509cert' => '',
                                                    'privateKey' => ''
                                               )
        */
        'signMetadata' => false,

        /** signatures and encryptions required **/

        // Indicates a requirement for the <samlp:Response>, <samlp:LogoutRequest>
        // and <samlp:LogoutResponse> elements received by this SP to be signed.
        'wantMessagesSigned' => false,

        // Indicates a requirement for the <saml:Assertion> elements received by
        // this SP to be encrypted.
        'wantAssertionsEncrypted' => false,

        // Indicates a requirement for the <saml:Assertion> elements received by
        // this SP to be signed. [Metadata of the SP will offer this info]
        'wantAssertionsSigned' => false,

        // Indicates a requirement for the NameID element on the SAMLResponse
        // received by this SP to be present.
        'wantNameId' => true,

        // Indicates a requirement for the NameID received by
        // this SP to be encrypted.
        'wantNameIdEncrypted' => false,

        // Authentication context.
        // Set to false and no AuthContext will be sent in the AuthNRequest.
        // Set true or don't present this parameter and you will get an AuthContext 'exact' 'urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport'.
        // Set an array with the possible auth context values: array ('urn:oasis:names:tc:SAML:2.0:ac:classes:Password', 'urn:oasis:names:tc:SAML:2.0:ac:classes:X509').
        'requestedAuthnContext' => false,

        // Indicates if the SP will validate all received xmls.
        // (In order to validate the xml, 'strict' and 'wantXMLValidation' must be true).
        'wantXMLValidation' => true,

        // If true, SAMLResponses with an empty value at its Destination
        // attribute will not be rejected for this fact.
        'relaxDestinationValidation' => false,

        // If true, the toolkit will not raised an error when the Statement Element
        // contain atribute elements with name duplicated
        'allowRepeatAttributeName' => false,

        // If true, Destination URL should strictly match to the address to
        // which the response has been sent.
        // Notice that if 'relaxDestinationValidation' is true an empty Destintation
        // will be accepted.
        'destinationStrictlyMatches' => false,

        // If true, SAMLResponses with an InResponseTo value will be rejectd if not
        // AuthNRequest ID provided to the validation method.
        'rejectUnsolicitedResponsesWithInResponseTo' => false,

        // Algorithm that the toolkit will use on signing process. Options:
        //    'http://www.w3.org/2000/09/xmldsig#rsa-sha1'
        //    'http://www.w3.org/2000/09/xmldsig#dsa-sha1'
        //    'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256'
        //    'http://www.w3.org/2001/04/xmldsig-more#rsa-sha384'
        //    'http://www.w3.org/2001/04/xmldsig-more#rsa-sha512'
        // Notice that sha1 is a deprecated algorithm and should not be used
        'signatureAlgorithm' => 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256',

        // Algorithm that the toolkit will use on digest process. Options:
        //    'http://www.w3.org/2000/09/xmldsig#sha1'
        //    'http://www.w3.org/2001/04/xmlenc#sha256'
        //    'http://www.w3.org/2001/04/xmldsig-more#sha384'
        //    'http://www.w3.org/2001/04/xmlenc#sha512'
        // Notice that sha1 is a deprecated algorithm and should not be used
        'digestAlgorithm' => 'http://www.w3.org/2001/04/xmlenc#sha256',

        // ADFS URL-Encodes SAML data as lowercase, and the toolkit by default uses
        // uppercase. Turn it True for ADFS compatibility on signature verification
        'lowercaseUrlencoding' => false,
    ),

    // Contact information template, it is recommended to supply a
    // technical and support contacts.
    'contactPerson' => array (
        'technical' => array (
            'givenName' => '',
            'emailAddress' => ''
        ),
        'support' => array (
            'givenName' => '',
            'emailAddress' => ''
        ),
    ),

    // Organization information template, the info in en_US lang is
    // recomended, add more if required.
    'organization' => array (
        'en-US' => array(
            'name' => '',
            'displayname' => '',
            'url' => ''
        ),
    ),
);

压缩设置允许您指示IdP是否可以接受使用gzip压缩的数据(请求和响应)。但是,如果我们将布尔参数$deflate提供给getRequest或getResponse方法,则它将优先于压缩设置。

在安全部分,您可以设置SP处理消息和断言的方式。联系IdP的管理员,询问其期望的内容,并决定SP将如何处理验证以及SP有哪些要求,并将这些信息传达给IdP管理员。

一旦我们知道可以配置哪种类型的数据,让我们来谈谈工具包中设置的处理方式。

下面描述的设置文件(settings.phpadvanced_settings.php)在工具包构造函数中未提供其他设置信息数组时,将由工具包加载。让我们看看一些例子。

// Initializes toolkit with settings.php & advanced_settings files.
$auth = new OneLogin_Saml2_Auth();
//or
$settings = new OneLogin_Saml2_Settings();

// Initializes toolkit with the array provided.
$auth = new OneLogin_Saml2_Auth($settingsInfo);
//or
$settings = new OneLogin_Saml2_Settings($settingsInfo);

您可以在包含构造函数执行文件的文件中声明 $settingsInfo,或者将它们放在任何文件中,然后加载该文件,以便获得如下示例中可见的数组。

<?php

require_once 'custom_settings.php';  // The custom_settings.php contains a
                                     // $settingsInfo array.

$auth = new OneLogin_Saml2_Auth($settingsInfo);

如何加载库

为了使用工具包库,您需要导入位于工具包基本文件夹中的 _toolkit_loader.php 文件。您可以这样加载这个文件:

<?php

define("TOOLKIT_PATH", '/var/www/php-saml/');
require_once(TOOLKIT_PATH . '_toolkit_loader.php');

在那行之后,我们将能够使用工具包的类(及其方法)(因为外部和Saml2库文件已被加载)。

如果您为PHP-SAML工具包的第1版编写了SAML应用的代码,您将需要加载 compatibility.php 文件,该文件加载SAML库文件,除了 _toolkit_loader.php 之外。

该SAML库使用工具包最新版本的最新类和方法,但保留了旧过程的老旧类、方法和工作流程,以完成相同的事情。

我们强烈建议迁移您的旧代码并使用新工具包的新API,因为有许多新功能您无法用旧代码处理。

启动SSO

为了向IdP发送 AuthNRequest

<?php

define("TOOLKIT_PATH", '/var/www/php-saml/');
require_once(TOOLKIT_PATH . '_toolkit_loader.php');   // We load the SAML2 lib

$auth = new OneLogin_Saml2_Auth(); // Constructor of the SP, loads settings.php
                                   // and advanced_settings.php
$auth->login();   // Method that sent the AuthNRequest

根据 advanced_settings.php 的安全信息('authnRequestsSigned'),AuthNRequest 将以签名或未签名的方式发送。

然后IdP将向用户的客户端返回SAML响应。客户端随后将带有此信息转发到SP的属性消费者服务。如果我们没有在登录方法中设置 'url' 参数,并且我们使用工具包提供的默认ACS(endpoints/acs.php),则ACS端点将重定向用户到启动SSO请求的文件。

我们可以设置一个 'returnTo' URL以改变工作流程,并将用户重定向到其他PHP文件。

$newTargetUrl = 'http://example.com/consume2.php';
$auth = new OneLogin_Saml2_Auth();
$auth->login($newTargetUrl);

登录方法可以接收其他六个可选参数

  • $parameters - 一个参数数组,它将被添加到HTTP-Redirect中的 GET
  • $forceAuthn - 当为true时,AuthNRequest 将设置 ForceAuthn='true'
  • $isPassive - 当为true时,AuthNRequest 将设置 Ispassive='true'
  • $strict - 如果为true,则我们留在那里(返回URL字符串);如果为false,则重定向
  • $setNameIdPolicy - 当为true时,AuthNRequest将设置一个nameIdPolicy元素。
  • $nameIdValueReq - 向IdP指示应进行认证的主题。

如果需要匹配未来的SAMLResponse ID和要发送的AuthNRequest ID,则必须提取并保存该AuthNRequest ID。

$ssoBuiltUrl = $auth->login(null, array(), false, false, true);
$_SESSION['AuthNRequestID'] = $auth->getLastRequestID();
header('Pragma: no-cache');
header('Cache-Control: no-cache, must-revalidate');
header('Location: ' . $ssoBuiltUrl);
exit();

SP端点

与SP相关有三个重要的视图:元数据视图、ACS视图和SLS视图。工具包在端点目录中提供了这些视图的示例。

SP元数据 endpoints/metadata.php

此代码将提供我们的SP的XML元数据文件,基于我们在设置文件中提供的信息。

<?php

define("TOOLKIT_PATH", '/var/www/php-saml/');
require_once dirname(TOOLKIT_PATH.'/_toolkit_loader.php');

try {
    $auth = new OneLogin_Saml2_Auth();
    $settings = $auth->getSettings();
    $metadata = $settings->getSPMetadata();
    $errors = $settings->validateMetadata($metadata);
    if (empty($errors)) {
        header('Content-Type: text/xml');
        echo $metadata;
    } else {
        throw new OneLogin_Saml2_Error(
            'Invalid SP metadata: '.implode(', ', $errors),
            OneLogin_Saml2_Error::METADATA_SP_INVALID
        );
    }
} catch (Exception $e) {
    echo $e->getMessage();
}

getSPMetadata 将根据 advanced_settings.php 的安全信息('signMetadata')返回签名或未签名的元数据。

在XML元数据公开之前,会进行检查以确保提供的信息是有效的。

而不是使用Auth对象,您可以直接使用

$settings = new OneLogin_Saml2_Settings($settingsInfo, true);

来获取设置对象,并且使用true参数我们将避免IdP设置验证。

属性消费者服务(ACS) endpoints/acs.php

此代码处理IdP通过用户的客户端转发给SP的SAML响应。

<?php

session_start();  // IMPORTANT: This is required in order to be able
                  // to store the user data in the session.

define("TOOLKIT_PATH", '/var/www/php-saml/');
require_once dirname(TOOLKIT_PATH.'/_toolkit_loader.php';

$auth = new OneLogin_Saml2_Auth();

if (isset($_SESSION) && isset($_SESSION['AuthNRequestID'])) {
    $requestID = $_SESSION['AuthNRequestID'];
} else {
    $requestID = null;
}

$auth->processResponse($requestID);
unset($_SESSION['AuthNRequestID']);

$errors = $auth->getErrors();

if (!empty($errors)) {
    echo '<p>', implode(', ', $errors), '</p>';
    exit();
}

if (!$auth->isAuthenticated()) {
    echo "<p>Not authenticated</p>";
    exit();
}

$_SESSION['samlUserdata'] = $auth->getAttributes();
$_SESSION['samlNameId'] = $auth->getNameId();
$_SESSION['samlNameIdFormat'] = $auth->getNameIdFormat();
$_SESSION['samlNameidNameQualifier'] = $auth->getNameIdNameQualifier();
$_SESSION['samlNameidSPNameQualifier'] = $auth->getNameIdSPNameQualifier();
$_SESSION['samlSessionIndex'] = $auth->getSessionIndex();

if (isset($_POST['RelayState']) && OneLogin_Saml2_Utils::getSelfURL() != $_POST['RelayState']) {
    // To avoid 'Open Redirect' attacks, before execute the
    // redirection confirm the value of $_POST['RelayState'] is a // trusted URL.
    $auth->redirectTo($_POST['RelayState']);
}

$attributes = $_SESSION['samlUserdata'];
$nameId = $_SESSION['samlNameId'];

echo '<h1>Identified user: '. htmlentities($nameId) .'</h1>';

if (!empty($attributes)) {
    echo '<h2>'._('User attributes:').'</h2>';
    echo '<table><thead><th>'._('Name').'</th><th>'._('Values').'</th></thead><tbody>';
    foreach ($attributes as $attributeName => $attributeValues) {
        echo '<tr><td>' . htmlentities($attributeName) . '</td><td><ul>';
        foreach ($attributeValues as $attributeValue) {
            echo '<li>' . htmlentities($attributeValue) . '</li>';
        }
        echo '</ul></td></tr>';
    }
    echo '</tbody></table>';
} else {
    echo _('No attributes found.');
}

处理SAML响应并检查是否有错误。它还验证用户是否已认证并将userdata存储在会话中。

此时有两种可能的替代方案

  1. 如果没有提供RelayState,我们可以在这种视图中显示用户数据或我们想要的任何方式。

  2. 如果提供了RelayState,则发生重定向。

注意,我们在重定向之前将用户数据保存在会话中,以便在RelayState视图中可用。

getAttributes方法

为了检索属性,我们可以使用

$attributes = $auth->getAttributes();

使用此方法,我们获取SAML响应断言中IdP提供的所有用户数据。

如果我们执行print_r($attributes),我们可能会得到

Array
(
    [cn] => Array
        (
            [0] => John
        )
    [sn] => Array
        (
            [0] => Doe
        )
    [mail] => Array
        (
            [0] => john.doe@example.com
        )
    [groups] => Array
        (
            [0] => users
            [1] => members
        )
)

每个属性名称都可以用作$attributes中的索引来获取值。每个属性值都是一个数组 - 单值属性是一个只有一个元素的数组。

以下代码是等效的

$attributes = $auth->getAttributes();
print_r($attributes['cn']);
print_r($auth->getAttribute('cn'));

在尝试获取属性之前,检查用户是否已认证。如果用户未认证或SAML断言中没有属性,则返回空数组。例如,如果我们调用getAttributes$auth->processResponse之前,则getAttributes()将返回空数组。

单一登出服务(SLS) endpoints/sls.php

此代码处理登出请求和登出响应。

<?php

session_start();  // IMPORTANT: This is required in order to be able
                  // to close the user session.

define("TOOLKIT_PATH", '/var/www/php-saml/');
require_once dirname(TOOLKIT_PATH.'/_toolkit_loader.php';

$auth = new OneLogin_Saml2_Auth();

if (isset($_SESSION) && isset($_SESSION['LogoutRequestID'])) {
    $requestID = $_SESSION['LogoutRequestID'];
} else {
    $requestID = null;
}

$auth->processSLO(false, $requestID);

$errors = $auth->getErrors();

if (empty($errors)) {
    echo 'Sucessfully logged out';
} else {
    echo implode(', ', $errors);
}

如果SLS端点收到登出响应,则验证响应并可能关闭会话

// part of the processSLO method

$logoutResponse = new OneLogin_Saml2_LogoutResponse($this->_settings, $_GET['SAMLResponse']);
if (!$logoutResponse->isValid($requestId)) {
    $this->_errors[] = 'invalid_logout_response';
} else if ($logoutResponse->getStatus() !== OneLogin_Saml2_Constants::STATUS_SUCCESS) {
    $this->_errors[] = 'logout_not_success';
} else {
    if (!$keepLocalSession) {
        OneLogin_Saml2_Utils::deleteLocalSession();
    }
}

如果SLS端点收到登出请求,则验证请求,关闭会话并向IdP的SLS端点发送登出响应。

// part of the processSLO method

$decoded = base64_decode($_GET['SAMLRequest']);
$request = gzinflate($decoded);
if (!OneLogin_Saml2_LogoutRequest::isValid($this->_settings, $request)) {
    $this->_errors[] = 'invalid_logout_request';
} else {
    if (!$keepLocalSession) {
        OneLogin_Saml2_Utils::deleteLocalSession();
    }

    $inResponseTo = $request->id;
    $responseBuilder = new OneLogin_Saml2_LogoutResponse($this->_settings);
    $responseBuilder->build($inResponseTo);
    $logoutResponse = $responseBuilder->getResponse();

    $parameters = array('SAMLResponse' => $logoutResponse);
    if (isset($_GET['RelayState'])) {
        $parameters['RelayState'] = $_GET['RelayState'];
    }

    $security = $this->_settings->getSecurityData();
    if (isset($security['logoutResponseSigned']) && $security['logoutResponseSigned']) {
        $signature = $this->buildResponseSignature($logoutResponse, $parameters['RelayState'], $security['signatureAlgorithm']);
        $parameters['SigAlg'] = $security['signatureAlgorithm'];
        $parameters['Signature'] = $signature;
    }

    $this->redirectTo($this->getSLOurl(), $parameters);
}

如果您没有使用默认的PHP会话,或者需要手动销毁会话,可以将回调方法作为第四个参数传递给processSLO方法

$keepLocalSession = False;
$callback = function () {
    // Destroy user session
};

$auth->processSLO($keepLocalSession, null, false, $callback);

如果我们不希望processSLO销毁会话,则将true参数传递给processSLO方法

$keepLocalSession = True;
$auth->processSLO($keepLocalSession);

启动SLO

为了向IdP发送登出请求

<?php

define("TOOLKIT_PATH", '/var/www/php-saml/');
require_once(TOOLKIT_PATH . '_toolkit_loader.php');

$auth = new OneLogin_Saml2_Auth();

$auth->logout();   // Method that sent the Logout Request.

还有八个可选参数可以设置

  • $returnTo - 用户登出后应返回的目标URL。
  • $parameters - 需要添加到GET中的额外参数。
  • $name_id - 将用于构建登出请求。如果未设置name_id参数,并且auth对象处理了包含NameId的SAML响应,则将使用此NameId
  • $session_index - SessionIndex用于标识用户的会话。
  • $stay - 如果我们想停留(返回URL字符串),则为True;如果我们要重定向,则为False。
  • $nameIdFormat - 将在登出请求中设置NameID格式。
  • $nameIdNameQualifier - 将在登出请求中设置NameID NameQualifier。
  • $nameIdSPNameQualifier - 将在登出请求中设置NameID SP NameQualifier。

根据advanced_settings.php'logoutRequestSigned')中的安全信息,登出请求将被签名或未签名发送。

身份提供者(IdP)将通过用户的客户端将注销响应返回给服务提供者(SP)的单点登出服务。如果我们没有在注销方法中设置一个 'url' 参数,并且正在使用工具包提供的默认单点登出服务(endpoints/sls.php),则单点登出服务端点将重定向用户到启动单点登出请求的文件。

我们可以设置一个 'returnTo' URL 来改变工作流程,并将用户重定向到其他 PHP 文件。

$newTargetUrl = 'http://example.com/loggedOut.php';
$auth = new OneLogin_Saml2_Auth();
$auth->logout($newTargetUrl);

具有所有参数的更复杂注销

$auth = new OneLogin_Saml2_Auth();
$returnTo = null;
$paramters = array();
$nameId = null;
$sessionIndex = null;
$nameIdFormat = null;
$nameIdNameQualifier = null;
$nameIdSPNameQualifier = null;

if (isset($_SESSION['samlNameId'])) {
    $nameId = $_SESSION['samlNameId'];
}
if (isset($_SESSION['samlSessionIndex'])) {
    $sessionIndex = $_SESSION['samlSessionIndex'];
}
if (isset($_SESSION['samlNameIdFormat'])) {
    $nameIdFormat = $_SESSION['samlNameIdFormat'];
}
if (isset($_SESSION['samlNameIdNameQualifier'])) {
    $nameIdNameQualifier = $_SESSION['samlNameIdNameQualifier'];
}
if (isset($_SESSION['samlNameIdSPNameQualifier'])) {
    $nameIdSPNameQualifier = $_SESSION['samlNameIdSPNameQualifier'];
}
$auth->logout($returnTo, $paramters, $nameId, $sessionIndex, false, $nameIdFormat, $nameIdNameQualifier, $nameIdSPNameQualifier);

如果需要对未来的注销响应 ID 和要发送的注销请求 ID 进行匹配,则必须提取并存储该注销请求 ID。

$sloBuiltUrl = $auth->logout(null, $paramters, $nameId, $sessionIndex, true);
$_SESSION['LogoutRequestID'] = $auth->getLastRequestID();
header('Pragma: no-cache');
header('Cache-Control: no-cache, must-revalidate');
header('Location: ' . $sloBuiltUrl);
exit();

示例视图,该视图启动单点登录请求并处理响应(是 acs 目标)

我们可以编写一个独特的文件来启动单点登录过程,处理响应,获取属性,启动单点登出并处理注销响应。

注意:请查阅包含该用例的 demo1 文件夹;在后面的章节中,我们将进一步详细解释 demo1 用例。

<?php

session_start();    // Initialize the session, we do that because
                    // Note that processResponse and processSLO
                    // methods could manipulate/close that session

require_once dirname(__DIR__).'/_toolkit_loader.php'; // Load Saml2 and external libs
require_once 'settings.php';    // Load the setting info as an Array

$auth = new OneLogin_Saml2_Auth($settingsInfo);  // Initialize the SP SAML instance

if (isset($_GET['sso'])) {    // SSO action.  Will send an AuthNRequest to the IdP
    $auth->login();
} else if (isset($_GET['sso2'])) {              // Another SSO action
    $returnTo = $spBaseUrl.'/demo1/attrs.php';  // but set a custom RelayState URL
    $auth->login($returnTo);
} else if (isset($_GET['slo'])) {  // SLO action. Will sent a Logout Request to IdP
    $auth->logout();
} else if (isset($_GET['acs'])) {  // Assertion Consumer Service
    $auth->processResponse();      // Process the Response of the IdP, get the
                                   // attributes and put then at
                                   // $_SESSION['samlUserdata']

    $errors = $auth->getErrors();  // This method receives an array with the errors
                                   // that could took place during the process

    if (!empty($errors)) {
        echo '<p>', implode(', ', $errors), '</p>';
    }
                                          // This check if the response was
    if (!$auth->isAuthenticated()) {      // sucessfully validated and the user
        echo "<p>Not authenticated</p>";  // data retrieved or not
        exit();
    }

    $_SESSION['samlUserdata'] = $auth->getAttributes(); // Retrieves user data
    if (isset($_POST['RelayState']) && OneLogin_Saml2_Utils::getSelfURL() != $_POST['RelayState']) {
        // To avoid 'Open Redirect' attacks, before execute the
        // redirection confirm the value of $_POST['RelayState'] is a // trusted URL.
        $auth->redirectTo($_POST['RelayState']);  // Redirect if there is a
    }                                             // relayState set
} else if (isset($_GET['sls'])) {   // Single Logout Service
    $auth->processSLO();            // Process the Logout Request & Logout Response
    $errors = $auth->getErrors(); // Retrieves possible validation errors
    if (empty($errors)) {
        echo '<p>Sucessfully logged out</p>';
    } else {
        echo '<p>', implode(', ', $errors), '</p>';
    }
}

if (isset($_SESSION['samlUserdata'])) {   // If there is user data we print it.
    if (!empty($_SESSION['samlUserdata'])) {
        $attributes = $_SESSION['samlUserdata'];
        echo 'You have the following attributes:<br>';
        echo '<table><thead><th>Name</th><th>Values</th></thead><tbody>';
        foreach ($attributes as $attributeName => $attributeValues) {
            echo '<tr><td>' . htmlentities($attributeName) . '</td><td><ul>';
            foreach ($attributeValues as $attributeValue) {
                echo '<li>' . htmlentities($attributeValue) . '</li>';
            }
            echo '</ul></td></tr>';
        }
        echo '</tbody></table>';
    } else {                             // If there is not user data, we notify
        echo "<p>You don't have any attribute</p>";
    }

    echo '<p><a href="?slo" >Logout</a></p>'; // Print some links with possible
} else {                                      // actions
    echo '<p><a href="?sso" >Login</a></p>';
    echo '<p><a href="?sso2" >Login and access to attrs.php page</a></p>';
}

示例(使用 Composer)启动单点登录请求并处理响应(是 acs 目标)

通过 composer 安装包

composer require onelogin/php-saml

创建一个 index.php

<?php
require('vendor/autoload.php');

session_start();
$needsAuth = empty($_SESSION['samlUserdata']);

if ($needsAuth) {
    // put SAML settings into an array to avoid placing files in the
    // composer vendor/ directories
    $samlsettings = array(/*...config goes here...*/);

    $auth = new \OneLogin\Saml2\Auth($samlsettings);

    if (!empty($_REQUEST['SAMLResponse']) && !empty($_REQUEST['RelayState'])) {
        $auth->processResponse(null);
        $errors = $auth->getErrors();
        if (empty($errors)) {
            // user has authenticated successfully
            $needsAuth = false;
            $_SESSION['samlUserdata'] = $auth->getAttributes();
        }
    }

    if ($needsAuth) {
        $auth->login();
    }
}

// rest of your app goes here

URL 猜测方法

php-saml 工具包使用 OneLogin_Saml2_Utils 中的许多方法来猜测处理 SAML 消息的 URL。

  • getSelfHost 返回当前主机。
  • getSelfPort 返回用于请求的端口号。
  • isHTTPS 检查协议是否为 https 或 http。
  • getSelfURLhost 返回协议 + 当前主机 + 端口(如果与常见端口不同)。
  • getSelfURL 返回当前主机 + 当前视图 + 查询。
  • getSelfURLNoQuery 返回当前主机 + 当前视图的 URL。
  • getSelfRoutedURLNoQuery 返回当前主机 + 当前视图的定向 URL。

getSelfURLNoQuery 和 getSelfRoutedURLNoQuery 用于计算当前 URL,以验证 SAML 元素,如目标或接收者。

当 PHP 应用程序位于代理或负载均衡器后面时,我们可以执行 setProxyVars(true)setSelfPort,而 isHTTPS 将负责处理 $_SERVER["HTTP_X_FORWARDED_PORT"]$_SERVER['HTTP_X_FORWARDED_PROTO'] 变量(否则它们将被忽略)。

此外,开发人员可以使用 setSelfProtocolsetSelfHostsetSelfPortgetBaseURLPath 来定义要由 isHTTPSgetSelfHostgetSelfPortgetBaseURLPath 返回的特定值。并且定义一个 setBasePath,以便在 getSelfURLgetSelfRoutedURLNoQuery 中使用,以替换从 $_SERVER["REQUEST_URI"] 提取的数据。

在设置中,开发人员将能够设置一个 'baseurl' 参数,该参数将自动使用 setBaseURL 来设置 setSelfProtocolsetSelfHostsetSelfPortsetBaseURLPath 的值。

在负载均衡器后面工作

在 SSL 转发的负载均衡器后面工作时,可能会失败匹配 SAML 响应的断言请求 URL 和目标属性。

您可以通过配置服务器以使其了解代理并返回请求的原 URL 来解决这个问题。

或者通过使用前面章节中描述的方法。

SP 密钥轮换

如果您计划更新 SP 的 x509cert 和 privateKey,可以将新的 x509cert 定义为 $settings['sp']['x509certNew'],它将被发布在 SP 元数据上,以便身份提供者可以读取它们并准备好轮换。

具有多个证书的 IdP

在某些场景中,IdP 使用不同的证书进行签名/加密,或者处于密钥轮换阶段,并且多个证书已发布在 IdP 元数据中。

为了处理这种情况,工具包提供了 $settings['idp']['x509certMulti'] 参数。

当使用该参数时,工具包将忽略 'x509cert''certFingerprint' 值。

《x509certMulti》是一个包含2个键的数组

  • 'signing'。一个包含将被用于验证IdP签名的证书的数组
  • 'encryption'。一个包含一个唯一证书的数组,该证书将被用于加密发送给IdP的数据

重放攻击

为了避免重放攻击,您可以存储已处理SAML消息的ID,以避免重复处理。由于消息会过期并且由于这个原因将失效,所以您不需要存储这些ID超过您目前接受的时间框架。

使用Auth对象的getLastMessageId/getLastAssertionId方法获取最后处理的消息/断言的ID。

主要类和方法

下面描述了可以调用的主要类和方法。

旧的SAML库

让我们先描述SAML库的类和方法,这是一个老版本1工具包的演变,它提供以保持向后兼容。其中大部分都使用新的SAML2库的类和方法。

OneLogin_Saml_AuthRequest - AuthRequest.php

有一个受保护的属性$auth,一个OneLogin_Saml2_Auth对象。

  • OneLogin_Saml_AuthRequest - 构造OneLogin_Saml2_Auth,初始化SP SAML实例。
  • getRedirectUrl($returnTo) - 获取包含压缩后的AuthRequest消息的SSO URL。
OneLogin_Saml_Response - Response.php
  • OneLogin_Saml_Response - 构造函数处理SAML响应,内部初始化SP SAML实例和OneLogin_Saml2_Response
  • get_saml_attributes - 获取包含已登录用户数据的数组。
OneLogin_Saml_Settings - Settings.php

一个简单的类,用于构建用于工具包v1.0的设置对象。

OneLogin_Saml_Metadata - Metadata.php
  • OneLogin_Saml_Metadata - 构造函数根据SP的设置构建元数据XML信息。
  • getXml - 包含SP元数据信息的XML。
OneLogin_Saml_XmlSec - XmlSec.php

一个辅助类,包含验证SAML响应的方法:validateNumAssertionsvalidateTimestampsisValid(它使用前面两种方法并也验证SAML响应的签名)。

SAML2库

现在让我们描述SAML2库的类和方法。

OneLogin_Saml2_Auth - Auth.php

PHP工具包的主要类

  • OneLogin_Saml2_Auth - 初始化SP SAML实例
  • login - 启动SSO过程。
  • logout - 启动SLO过程。
  • processResponse - 处理IdP发送的SAML响应。
  • processSLO - 处理IdP发送的SAML注销响应/注销请求。
  • redirectTo - 将用户重定向到参数中指定的URL或我们定义的SSO请求中的URL。
  • isAuthenticated - 检查用户是否已认证。
  • getAttributes - 返回SAML属性的集合。
  • getAttribute - 返回请求的SAML属性
  • getNameId - 返回nameID
  • getNameIdFormat - 获取IdP提供的NameID格式
  • getNameIdNameQualifier - 获取SAML响应字符串中提供的NameID NameQualifier
  • getNameIdSPNameQualifier - 获取SAML响应字符串中提供的NameID SP NameQualifier
  • getSessionIndex - 获取AuthnStatement中的SessionIndex
  • getErrors - 返回是否有错误
  • getSSOurl - 获取SSO URL。
  • getSLOurl - 获取SLO URL。
  • getLastRequestID - 最后生成的请求SAML消息的ID。
  • buildRequestSignature - 生成SAML请求的签名
  • buildResponseSignature - 生成SAML响应的签名
  • getSettings - 返回设置信息
  • setStrict - 设置严格模式启用/禁用
  • getLastRequestID - 获取由服务提供商生成的最后一个AuthNRequest或LogoutRequest的ID。
  • getLastRequestXML - 返回最近构造/处理的 XML SAML 请求(AuthNRequest, LogoutRequest)
  • getLastResponseXML - 返回最近构造/处理的 XML SAML 响应(SAMLResponse, LogoutResponse)。如果 SAMLResponse 包含加密断言,则对其进行解密。
OneLogin_Saml2_AuthnRequest - AuthnRequest.php

SAML 2 认证请求类

  • OneLogin_Saml2_AuthnRequest - 构建 AuthnRequest 对象。
  • getRequest - 返回压缩、base64 编码、未签名的 AuthnRequest
  • getId - 返回 AuthNRequest ID。
  • getXML - 返回作为请求一部分要发送的 XML。
OneLogin_Saml2_Response - Response.php

SAML 2 认证响应类

  • OneLogin_Saml2_Response - 构建 SAML 响应对象。
  • isValid - 使用证书确定 SAML 响应是否有效。
  • checkStatus - 检查状态是否为成功。
  • getAudiences - 获取受众。
  • getIssuers - 获取发行者(来自响应和断言)
  • getNameIdData - 获取来自 IdP 的 SAML 响应提供的 NameID 数据。
  • getNameId - 获取来自 IdP 的 SAML 响应提供的 NameID。
  • getNameIdFormat - 获取IdP提供的NameID格式
  • getNameIdNameQualifier - 获取SAML响应字符串中提供的NameID NameQualifier
  • getNameIdSPNameQualifier - 获取SAML响应字符串中提供的NameID SP NameQualifier
  • getSessionNotOnOrAfter - 从 AuthnStatement 获取 SessionNotOnOrAfter。
  • getSessionIndex - 获取AuthnStatement中的SessionIndex
  • getAttributes - 从 AttributeStatement 元素获取属性。
  • validateNumAssertions - 验证文档只包含单个断言(加密或未加密)。
  • validateTimestamps - 验证根据条件元素,文档是否仍然有效。
  • getError - 在执行验证过程后,如果失败,此方法返回原因
  • getXMLDocument - 返回 SAML 响应对象(如果包含加密断言,则对其进行解密)
OneLogin_Saml2_LogoutRequest - LogoutRequest.php

SAML 2 注销请求类

  • OneLogin_Saml2_LogoutRequest - 构建注销请求对象。
  • getRequest - 返回注销请求的压缩、base64 编码、未签名的数据。
  • getID - 返回注销请求的 ID。(如果您有对象,您可以访问 id 属性)
  • getNameIdData - 获取注销请求的 NameID 数据。
  • getNameId - 获取注销请求的 NameID。
  • getIssuer - 获取注销请求的发行者。
  • getSessionIndexes - 从注销请求获取 SessionIndexes。
  • isValid - 检查收到的注销请求是否有效。
  • getError - 在执行验证过程后,如果失败,此方法返回原因
  • getXML - 返回作为请求一部分要发送的 XML 或在 SP 收到的 XML。
OneLogin_Saml2_LogoutResponse - LogoutResponse.php

SAML 2 注销响应类

  • OneLogin_Saml2_LogoutResponse - 构建一个注销响应对象(从设置中初始化参数,如果提供,则加载注销响应)
  • getIssuer - 获取注销响应的发行者。
  • getStatus - 获取注销响应的状态。
  • isValid - 确定是否 SAML 注销响应有效
  • build - 生成注销响应对象。
  • getResponse - 返回注销响应对象。
  • getError - 在执行验证过程后,如果失败,此方法返回原因。
  • getXML - 返回作为响应一部分要发送的 XML 或在 SP 收到的 XML。
OneLogin_Saml2_Settings - Settings.php

PHP 工具包的配置

  • OneLogin_Saml2_Settings - 初始化设置:设置不同文件夹的路径并从设置文件或提供的数组/对象中加载设置信息
  • checkSettings - 检查设置信息。
  • getBasePath - 返回基本路径。
  • getCertPath - 返回证书路径。
  • getLibPath - 返回库路径。
  • getExtLibPath - 返回外部库路径。
  • getSchemasPath - 返回模式路径。
  • checkSPCerts - 检查SP的x509证书是否存在且有效。
  • getSPkey - 返回SP的x509私钥。
  • getSPcert - 返回SP的x509公钥证书。
  • getSPcertNew - 返回SP未来的x509公钥证书。
  • getIdPData - 获取IdP数据。
  • getSPData 获取SP数据。
  • getSecurityData - 获取安全数据。
  • getContacts - 获取联系数据。
  • getOrganization - 获取组织数据。
  • getSPMetadata - 获取SP元数据。XML表示形式。
  • validateMetadata - 验证XML SP元数据。
  • formatIdPCert - 格式化IdP证书。
  • formatSPCert - 格式化SP证书。
  • formatSPCertNew - 格式化SP证书新格式。
  • formatSPKey - 格式化SP私钥。
  • getErrors - 返回一个包含错误的数组,当设置正常时数组为空。
  • getLastErrorReason - 返回最后一个错误的原因。
  • getBaseURL - 如果有设置,返回设置的baseurl。
  • setBaseURL - 设置baseurl值。
  • setStrict - 启用或禁用严格模式。
  • isStrict - 返回是否启用了'严格'模式。
  • isDebugActive - 返回是否启用了调试。
OneLogin_Saml2_Metadata - Metadata.php

一个包含与SP元数据相关功能的类

  • builder - 根据设置生成SP的元数据。
  • signmetadata - 使用提供的密钥/证书签名元数据。
  • addX509KeyDescriptors - 将x509描述符(签名/加密)添加到元数据中。
OneLogin_Saml2_Utils - Utils.php

一个包含多个方法的辅助类

  • validateXML - 此函数尝试将XML字符串与指定的模式进行验证。
  • formatCert - 返回一个x509证书(如果需要,添加头和尾)。
  • formatPrivateKey - 返回一个RSA私钥(如果需要,添加头和尾)。
  • redirect - 执行到提供的url的重定向(或返回目标url)。
  • isHTTPS - 检查是否为https或http。
  • getSelfHost - 返回当前主机。
  • getSelfURLhost - 返回协议 + 当前主机 + 端口(如果不同于常用端口)。
  • getSelfURLNoQuery - 返回当前主机 + 当前视图的URL。
  • getSelfURL - 返回当前主机 + 当前视图 + 查询的URL。
  • generateUniqueID - 生成一个唯一的字符串(例如,用作断言的ID)。
  • parseTime2SAML - 将UNIX时间戳转换为SAML2时间戳,格式为yyyy-mm-ddThh:mm:ss(.s+)?Z
  • parseSAML2Time - 将格式为yyyy-mm-ddThh:mm:ss(.s+)?Z的SAML2时间戳转换为UNIX时间戳。忽略亚秒部分。
  • parseDuration - 解析相对于给定时间戳的ISO8601持续时间值。
  • getExpireTime - 比较两个日期并返回最早的。
  • query - 从DOMDocument中提取节点。
  • isSessionStarted - 检查会话是否已启动。
  • deleteLocalSession - 删除本地会话。
  • calculateX509Fingerprint - 计算x509证书的指纹。
  • formatFingerPrint - 格式化指纹。
  • generateNameId - 生成一个nameID
  • getStatus - 从响应中获取状态。
  • decryptElement - 解密加密的元素。
  • castKey - 将XMLSecurityKey转换为正确的算法。
  • addSign - 将签名密钥和发送者证书添加到元素(消息或断言)中。
  • validateSign - 验证签名(消息或断言)。
OneLogin_Saml2_IdPMetadataParser - IdPMetadataParser.php

一个包含多个方法来检索和处理IdP元数据的辅助类

  • parseRemoteXML - 从URL获取IdP元数据信息。
  • parseFileXML - 从文件获取IdP元数据信息。
  • parseXML - 从XML中获取IdP元数据信息。
  • injectIntoSettings - 将元数据信息注入php-saml设置数组中。

该类不会以任何方式验证在方法如parseRemoteXML中引入的URL,以检索远程XML。通常,处理服务提供者的管理员会设置应属于受信任第三方IdP的URL。但存在其他场景,如SAAS应用程序,其中应用程序管理员将权限委托给其他管理员。在这种情况下,应采取额外保护来验证此类URL输入,以避免如SSRF之类的攻击。

有关更多信息,请查看源代码;每个方法都有文档,并提供关于其功能和使用方法的详细信息。请确保检查doc文件夹,其中提供了关于SAML和SAML2的类和方法的HTML文档。

工具包中包含的演示

该工具包包括三个演示应用程序,以教授如何使用工具包,请查看。

在测试之前,演示需要确保SP和IdP配置良好。

Demo1

SP设置

PHP工具包允许您以两种方式提供设置信息

  • 使用位于工具包基本文件夹中的settings.php文件。
  • 使用设置数据的数组。

在此演示中,我们以第二种方式提供数据,使用名为$settingsInfo的设置数组。此数组使用包含的settings_example.php模板来创建settings.php设置并将其存储在demo1/文件夹中。配置SP部分,然后审查IdP的元数据并完成IdP信息。

如果您检查index.php文件的代码,您将看到正在加载settings.php文件,以便使用$settingsInfo变量来初始化Setting类。

请注意,在此演示中,可以定义在工具包基本文件夹中的setting.php文件被忽略,并且使用位于工具包基本文件夹中的_toolkit_loader.php加载库。

IdP设置

一旦配置了SP,SP的元数据就会发布到metadata.php文件。根据该信息配置IdP。

工作原理

  1. 首次访问index.php视图时,您可以选择登录并返回到同一视图或登录并重定向到attrs.php视图。

  2. 当您点击

    第一个链接中的2.1,我们访问到(index.php?sso),向IdP发送一个AuthNRequest,我们在IdP进行身份验证,然后通过用户的客户端将响应发送到SP,特别是Assertion Consumer Service视图:index.php?acs。注意,已将RelayState参数设置为启动过程的URL,即index.php视图。

    第二个链接中的2.2与2.1中描述的过程相同,不同之处在于将RelayState设置为attrs.php

  3. SAML响应在ACS(index.php?acs)中处理,如果响应无效,则在此停止处理并显示消息。否则,我们将重定向到RelayState视图。a) index.php或b) attrs.php

  4. 我们在应用程序中登录,并显示用户属性。在此阶段,我们可以测试单点退出功能。

  5. 单点退出功能可以通过两种方式测试。

    5.1 SP启动SLO。在SP中点击“退出”链接,之后向IdP发送一个退出请求,关闭IdP中的会话,并通过客户端向SP发送退出响应(发送到单点退出服务端点)。SP的单点退出端点(index.php?sls)处理退出响应,如果有效,则关闭本地应用程序的用户会话。请注意,SLO工作流程从SP开始并结束。

    5.2 由IdP发起的SLO。在这种情况下,操作发生在IdP端,注销过程在idP端启动,向SP发送注销请求(SLS端点,index.php?sls)。SP处理注销请求,如果有效,关闭本地应用的用户会话,并向IdP(IdP的SLS端点)发送注销响应。IdP收到注销响应,进行处理,并关闭IdP的会话。注意,SLO工作流程始于IdP并结束于IdP。

注意,所有SAML请求和响应都由一个唯一的文件处理,即index.php文件,以及如何使用GET参数来确定必须执行的操作。

Demo2

SP设置

PHP工具包允许您以两种方式提供设置信息

  • 使用位于工具包基本文件夹中的settings.php文件。
  • 使用设置数据的数组。

第一个是demo2应用的案例。应该在工具包的基本文件夹中定义setting.php文件和setting_extended.php文件。通过查看setting_example.phpadvanced_settings_example.php来学习如何构建它们。

在这种情况下,我们将使用位于端点文件夹中的文件(acs.phpsls.php)作为属性消费服务和单点注销服务。

IdP设置

一旦配置了SP,SP的元数据将发布在metadata.php文件中。基于此信息,配置IdP。

工作原理

在demo1中,我们看到了所有SAML请求和响应都在一个唯一的文件index.php中处理。这个demo1使用高级编程。

在demo2中,我们有几个视图:index.phpsso.phpslo.phpconsume.phpmetadata.php。正如我们所言,我们将使用工具包中定义的端点(端点文件夹中的acs.phpsls.php)。这个demo2使用低级编程。

注意,SSO操作可以从index.phpsso.php开始。

发生的SAML工作流程与demo1中定义的工作流程类似,只是改变了目标。

  1. 当您第一次访问index.phpsso.php时,会自动向IdP发送一个AuthNRequest(因为发送了原始url作为RelayState)。我们在IdP进行认证,然后向SP发送一个响应(发送到ACS端点,在这种情况下是端点文件夹中的acs.php)。

  2. 在ACS中处理SAML响应,如果响应无效,则在此处停止处理并显示消息。否则,我们将重定向到RelayState视图(sso.phpindex.php)。sso.php检测用户是否已登录,并将其重定向到index.php,所以最终我们将位于index.php

  3. 我们已登录到应用,并显示用户属性(如果有)。在此阶段,我们可以测试单点注销功能。

  4. 单点退出功能可以通过两种方式测试。

    4.1 由SP发起的SLO。点击SP中的“注销”链接,之后我们将重定向到slo.php视图,在那里向IdP发送一个注销请求,关闭IdP的会话,并向SP回复注销响应(发送到单点注销服务端点)。在这种情况下,SP的SLS端点处理注销响应,如果有效,关闭本地应用的用户会话。注意,SLO工作流程始于SP并结束于SP。

    4.2 由身份提供者(IdP)发起的SLO。在这种情况下,操作发生在IdP端,注销过程在idP端启动,向服务提供商(SP)发送注销请求(端点文件夹中的SLS端点 sls.php)。SP处理注销请求,如果请求有效,则在本地应用程序中关闭用户的会话,并向IdP(IdP的SLS端点)发送注销响应。IdP收到注销响应,处理后关闭IdP的会话。请注意,SLO工作流始于IdP并结束于IdP。

旧版演示

SP设置

此演示使用工具包版本的1的旧风格。必须向AuthRequest的构造函数提供OneLogin_Saml_Settings类的对象。

您可以在demo-old文件夹中找到example_settings.php文件,该文件可以用作您的settings.php文件的模板。

在该模板中,SAML设置分为两部分,应用特定(const_assertion_consumer_service_urlconst_issuerconst_name_identifier_format)和用户/账户特定(idp_sso_target_urlx509certificate)。您需要在此处添加自己的代码来识别用户或用户来源(例如,通过subdomainip_address等)。

IdP设置

配置SP后,SP的元数据在metadata.php文件中发布。之后,根据该信息配置IdP。

工作原理

metadata.php视图中发布了SP的元数据。

index.php文件在应用程序应启动SAML会话时充当初始化器。这称为服务提供商初始化的SAML。服务提供商创建SAML认证请求并将其发送给身份提供者(IdP)。

consume.php是ACS端点。接收SAML断言。在响应验证后,可以使用getNameId()getAttributes()获取用户数据和nameID。

由于php工具包的1版本不支持SLO,我们在此旧版演示中不展示如何处理SLO。