{"id":44989731,"url":"https://github.com/iwouldrathercode/php-custom-one-login","last_synced_at":"2026-02-18T21:12:47.097Z","repository":{"id":56994963,"uuid":"271723030","full_name":"iwouldrathercode/php-custom-one-login","owner":"iwouldrathercode","description":"Opinionated fork of OneLogin's SAML PHP Toolkit Compatible with PHP 5.X \u0026 7.X and upgrades for usage as a dependency for the iwouldrathercode/php-simple-ad-connect","archived":false,"fork":false,"pushed_at":"2022-10-14T03:46:23.000Z","size":1015,"stargazers_count":1,"open_issues_count":1,"forks_count":1,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-10-20T21:13:24.280Z","etag":null,"topics":["dependency","one-login","php","saml-authentication"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/iwouldrathercode.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2020-06-12T06:13:48.000Z","updated_at":"2023-05-23T15:30:43.000Z","dependencies_parsed_at":"2022-08-21T10:40:46.832Z","dependency_job_id":null,"html_url":"https://github.com/iwouldrathercode/php-custom-one-login","commit_stats":null,"previous_names":[],"tags_count":10,"template":false,"template_full_name":null,"purl":"pkg:github/iwouldrathercode/php-custom-one-login","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/iwouldrathercode%2Fphp-custom-one-login","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/iwouldrathercode%2Fphp-custom-one-login/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/iwouldrathercode%2Fphp-custom-one-login/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/iwouldrathercode%2Fphp-custom-one-login/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/iwouldrathercode","download_url":"https://codeload.github.com/iwouldrathercode/php-custom-one-login/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/iwouldrathercode%2Fphp-custom-one-login/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29596189,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-18T20:59:56.587Z","status":"ssl_error","status_checked_at":"2026-02-18T20:58:41.434Z","response_time":162,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["dependency","one-login","php","saml-authentication"],"created_at":"2026-02-18T21:12:46.195Z","updated_at":"2026-02-18T21:12:47.089Z","avatar_url":"https://github.com/iwouldrathercode.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# iwouldrathercode/php-custom-one-login\n\n[![Latest Version on Packagist](https://img.shields.io/packagist/v/iwouldrathercode/cognito.svg?style=flat-square)](https://packagist.org/packages/iwouldrathercode/php-custom-one-login)\n[![Total Downloads](https://img.shields.io/packagist/dt/iwouldrathercode/cognito.svg?style=flat-square)](https://packagist.org/packages/iwouldrathercode/php-custom-one-login)\n\nOpinionated fork of OneLogin's SAML PHP Toolkit Compatible with PHP 5.X \u0026 7.X and upgrades for usage as a dependency for the iwouldrathercode/php-simple-ad-connect.\n\nWarning\n-------\n\nThis version is compatible with PHP 7.X and does not include xmlseclibs (you will need to install it via composer, dependency described in composer.json)\n\nSecurity Guidelines\n-------------------\n\nIf you believe you have discovered a security vulnerability in this toolkit, please report it at https://www.onelogin.com/security with a description. We follow responsible disclosure guidelines, and will work with you to quickly find a resolution.\n\n\nWhy add SAML support to my software?\n------------------------------------\n\nSAML is an XML-based standard for web browser single sign-on and is defined by\nthe OASIS Security Services Technical Committee. The standard has been around\nsince 2002, but lately it is becoming popular due its advantages:\n\n * **Usability** - One-click access from portals or intranets, deep linking,\n   password elimination and automatically renewing sessions make life\n   easier for the user.\n * **Security** - Based on strong digital signatures for authentication and\n   integrity, SAML is a secure single sign-on protocol that the largest\n   and most security conscious enterprises in the world rely on.\n * **Speed** - SAML is fast. One browser redirect is all it takes to securely\n   sign a user into an application.\n * **Phishing Prevention** - If you don’t have a password for an app, you\n   can’t be tricked into entering it on a fake login page.\n * **IT Friendly** - SAML simplifies life for IT because it centralizes\n   authentication, provides greater visibility and makes directory\n   integration easier.\n * **Opportunity** - B2B cloud vendor should support SAML to facilitate the\n   integration of their product.\n\n\nGeneral description\n-------------------\n\nOneLogin's SAML PHP toolkit let you build a SP (Service Provider) over\nyour PHP application and connect it to any IdP (Identity Provider).\n\nSupports:\n\n * SSO and SLO (SP-Initiated and IdP-Initiated).\n * Assertion and nameId encryption.\n * Assertion signature.\n * Message signature: AuthNRequest, LogoutRequest, LogoutResponses.\n * Enable an Assertion Consumer Service endpoint.\n * Enable a Single Logout Service endpoint.\n * Publish the SP metadata (which can be signed).\n\nKey features:\n\n * **saml2int** - Implements the SAML 2.0 Web Browser SSO Profile.\n * **Session-less** - Forget those common conflicts between the SP and\n   the final app, the toolkit delegate session in the final app.\n * **Easy to use** - Programmer will be allowed to code high-level and\n   low-level programming, 2 easy to use APIs are available.\n * **Tested** - Thoroughly tested.\n * **Popular** - OneLogin's customers use it. Many PHP SAML plugins uses it.\n\nIntegrate your PHP toolkit at OneLogin using this guide: [https://developers.onelogin.com/page/saml-toolkit-for-php](https://developers.onelogin.com/page/saml-toolkit-for-php)\n\nInstallation\n------------\n\n### Dependencies ###\n\n * `php \u003e= 5.4` and some core extensions like `php-xml`, `php-date`, `php-zlib`.\n * `openssl`. Install the openssl library. It handles x509 certificates.\n * `gettext`. Install that library and its php driver. It handles translations.\n * `curl`. Install that library and its php driver if you plan to use the IdP Metadata parser.\n\n### Code ###\n\n#### Option 1. Download from github ####\n\nThe toolkit is hosted on github. You can download it from:\n\n * https://github.com/onelogin/php-saml/releases\n\nSearch for 3.X.X releases\n\nCopy the core of the library inside the php application. (each application has its\nstructure so take your time to locate the PHP SAML toolkit in the best place).\nSee the \"Guide to add SAML support to my app\" to know how.\n\n#### Option 2. Composer ####\n\nThe toolkit supports [composer](https://getcomposer.org/). You can find the `onelogin/php-saml` package at https://packagist.org/packages/onelogin/php-saml\n\nIn order to import the saml toolkit to your current php project, execute\n```\ncomposer require onelogin/php-saml\n```\n\nRemember to select the 3.X.X branch\n\nAfter installation has completed you will find at the `vendor/` folder a new folder named `onelogin` and inside the `php-saml`. Make sure you are including the autoloader provided by composer. It can be found at `vendor/autoload.php`.\n\n**Important** In this option, the x509 certs must be stored at `vendor/onelogin/php-saml/certs`\nand settings file stored at `vendor/onelogin/php-saml`.\n\nYour settings are at risk of being deleted when updating packages using `composer update` or similar commands. So it is **highly** recommended that instead of using settings files, you pass the settings as an array directly to the constructor (explained later in this document). If you do not use this approach your settings are at risk of being deleted when updating packages using `composer update` or similar commands.\n\nCompatibility\n-------------\n\nThis 3.X.X supports PHP 7.X. but can be used with PHP \u003e=5.4 as well  (5.6.24+ recommended for security reasons).\n\nNamespaces\n----------\n\nIf you are using the library with a framework like Symfony that contains\nnamespaces, remember that calls to the class must be done by adding a backslash (`\\`) to the\nstart, for example to use the static method getSelfURLNoQuery use:\n\n    \\OneLogin\\Saml2\\Utils::getSelfURLNoQuery()\n\n\nSecurity warning\n----------------\n\nIn production, the `strict` parameter **MUST** be set as `\"true\"` and the\n`signatureAlgorithm` and `digestAlgorithm` under `security` must be set to\nsomething other than SHA1 (see https://shattered.io/ ). Otherwise your\nenvironment is not secure and will be exposed to attacks.\n\nIn production also we highly recommended to register on the settings the IdP certificate instead of using the fingerprint method. The fingerprint, is a hash, so at the end is open to a collision attack that can end on a signature validation bypass. Other SAML toolkits deprecated that mechanism, we maintain it for compatibility and also to be used on test environment.\n\nGetting started\n---------------\n\n### Knowing the toolkit ###\n\nThe new OneLogin SAML Toolkit contains different folders (`certs`, `endpoints`,\n`lib`, `demo`, etc.) and some files.\n\nLet's start describing the folders:\n\n#### `certs/` ####\n\nSAML requires a x509 cert to sign and encrypt elements like `NameID`, `Message`,\n`Assertion`, `Metadata`.\n\nIf our environment requires sign or encrypt support, this folder may contain\nthe x509 cert and the private key that the SP will use:\n\n * `sp.crt` - The public cert of the SP\n * `sp.key` - The private key of the SP\n\nOr also we can provide those data in the setting file at the `$settings['sp']['x509cert']`\nand the `$settings['sp']['privateKey']`.\n\nSometimes we could need a signature on the metadata published by the SP, in\nthis case we could use the x509 cert previously mentioned or use a new x.509\ncert: `metadata.crt` and `metadata.key`.\n\nUse `sp_new.crt` if you are in a key rollover process and you want to\npublish that x509 certificate on Service Provider metadata.\n\n#### `src/` ####\n\nThis folder contains the heart of the toolkit, the libraries:\n\n * `Saml2` folder contains the new version of the classes and methods that\n   are described in a later section.\n\n\n#### `doc/` ####\n\nThis folder contains the API documentation of the toolkit.\n\n\n#### `endpoints/` ####\n\nThe toolkit has three endpoints:\n\n * `metadata.php` - Where the metadata of the SP is published.\n * `acs.php` - Assertion Consumer Service. Processes the SAML Responses.\n * `sls.php` - Single Logout Service. Processes Logout Requests and Logout\n   Responses.\n\nYou can use the files provided by the toolkit or create your own endpoints\nfiles when adding SAML support to your applications. Take in mind that those\nendpoints files uses the setting file of the toolkit's base folder.\n\n\n#### `locale/` ####\n\nLocale folder contains some translations: `en_US` and `es_ES` as a proof of concept.\nCurrently there are no translations but we will eventually localize the messages\nand support multiple languages.\n\n\n#### Other important files ####\n\n* `settings_example.php` - A template to be used in order to create a\n  settings.php file which contains the basic configuration info of the toolkit.\n* `advanced_settings_example.php` - A template to be used in order to create a\n  advanced_settings.php file which contains extra configuration info related to\n  the security, the contact person, and the organization associated to the SP.\n* `_toolkit_loader.php` - This file load the toolkit libraries (The SAML2 lib).\n\n\n#### Miscellaneous ####\n\n* `tests/` - Contains the unit test of the toolkit.\n* `demo1/` - Contains an example of a simple PHP app with SAML support.\n  Read the `Readme.txt` inside for more info.\n* `demo2/` - Contains another example.\n\n\n### How it works ###\n\n#### Settings ####\n\nFirst of all we need to configure the toolkit. The SP's info, the IdP's info,\nand in some cases, configure advanced security issues like signatures and\nencryption.\n\nThere are two ways to provide the settings information:\n\n * Use a `settings.php` file that we should locate at the base folder of the\n   toolkit.\n * Use an array with the setting data and provide it directly to the\n   constructor of the class.\n\n\nThere is a template file, `settings_example.php`, so you can make a copy of this\nfile, rename and edit it.\n\n```php\n\u003c?php\n\n$settings = array(\n    // If 'strict' is True, then the PHP Toolkit will reject unsigned\n    // or unencrypted messages if it expects them to be signed or encrypted.\n    // Also it will reject the messages if the SAML standard is not strictly\n    // followed: Destination, NameId, Conditions ... are validated too.\n    'strict' =\u003e false,\n\n    // Enable debug mode (to print errors).\n    'debug' =\u003e false,\n\n    // Set a BaseURL to be used instead of try to guess\n    // the BaseURL of the view that process the SAML Message.\n    // Ex http://sp.example.com/\n    //    http://example.com/sp/\n    'baseurl' =\u003e null,\n\n    // Service Provider Data that we are deploying.\n    'sp' =\u003e array(\n        // Identifier of the SP entity  (must be a URI)\n        'entityId' =\u003e '',\n        // Specifies info about where and how the \u003cAuthnResponse\u003e message MUST be\n        // returned to the requester, in this case our SP.\n        'assertionConsumerService' =\u003e array(\n            // URL Location where the \u003cResponse\u003e from the IdP will be returned\n            'url' =\u003e '',\n            // SAML protocol binding to be used when returning the \u003cResponse\u003e\n            // message. OneLogin Toolkit supports this endpoint for the\n            // HTTP-POST binding only.\n            'binding' =\u003e 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST',\n        ),\n        // If you need to specify requested attributes, set a\n        // attributeConsumingService. nameFormat, attributeValue and\n        // friendlyName can be omitted\n        \"attributeConsumingService\"=\u003e array(\n                \"serviceName\" =\u003e \"SP test\",\n                \"serviceDescription\" =\u003e \"Test Service\",\n                \"requestedAttributes\" =\u003e array(\n                    array(\n                        \"name\" =\u003e \"\",\n                        \"isRequired\" =\u003e false,\n                        \"nameFormat\" =\u003e \"\",\n                        \"friendlyName\" =\u003e \"\",\n                        \"attributeValue\" =\u003e array()\n                    )\n                )\n        ),\n        // Specifies info about where and how the \u003cLogout Response\u003e message MUST be\n        // returned to the requester, in this case our SP.\n        'singleLogoutService' =\u003e array(\n            // URL Location where the \u003cResponse\u003e from the IdP will be returned\n            'url' =\u003e '',\n            // SAML protocol binding to be used when returning the \u003cResponse\u003e\n            // message. OneLogin Toolkit supports the HTTP-Redirect binding\n            // only for this endpoint.\n            'binding' =\u003e 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect',\n        ),\n        // Specifies the constraints on the name identifier to be used to\n        // represent the requested subject.\n        // Take a look on lib/Saml2/Constants.php to see the NameIdFormat supported.\n        'NameIDFormat' =\u003e 'urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress',\n        // Usually x509cert and privateKey of the SP are provided by files placed at\n        // the certs folder. But we can also provide them with the following parameters\n        'x509cert' =\u003e '',\n        'privateKey' =\u003e '',\n\n        /*\n         * Key rollover\n         * If you plan to update the SP x509cert and privateKey\n         * you can define here the new x509cert and it will be\n         * published on the SP metadata so Identity Providers can\n         * read them and get ready for rollover.\n         */\n        // 'x509certNew' =\u003e '',\n    ),\n\n    // Identity Provider Data that we want connected with our SP.\n    'idp' =\u003e array(\n        // Identifier of the IdP entity  (must be a URI)\n        'entityId' =\u003e '',\n        // SSO endpoint info of the IdP. (Authentication Request protocol)\n        'singleSignOnService' =\u003e array(\n            // URL Target of the IdP where the Authentication Request Message\n            // will be sent.\n            'url' =\u003e '',\n            // SAML protocol binding to be used when returning the \u003cResponse\u003e\n            // message. OneLogin Toolkit supports the HTTP-Redirect binding\n            // only for this endpoint.\n            'binding' =\u003e 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect',\n        ),\n        // SLO endpoint info of the IdP.\n        'singleLogoutService' =\u003e array(\n            // URL Location of the IdP where SLO Request will be sent.\n            'url' =\u003e '',\n            // SAML protocol binding to be used when returning the \u003cResponse\u003e\n            // message. OneLogin Toolkit supports the HTTP-Redirect binding\n            // only for this endpoint.\n            'binding' =\u003e 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect',\n        ),\n        // Public x509 certificate of the IdP\n        'x509cert' =\u003e '',\n        /*\n         *  Instead of use the whole x509cert you can use a fingerprint in order to\n         *  validate a SAMLResponse, but we don't recommend to use that\n         *  method on production since is exploitable by a collision attack.\n         *  (openssl x509 -noout -fingerprint -in \"idp.crt\" to generate it,\n         *   or add for example the -sha256 , -sha384 or -sha512 parameter)\n         *\n         *  If a fingerprint is provided, then the certFingerprintAlgorithm is required in order to\n         *  let the toolkit know which algorithm was used. Possible values: sha1, sha256, sha384 or sha512\n         *  'sha1' is the default value.\n         *\n         *  Notice that if you want to validate any SAML Message sent by the HTTP-Redirect binding, you\n         *  will need to provide the whole x509cert.\n         */\n        // 'certFingerprint' =\u003e '',\n        // 'certFingerprintAlgorithm' =\u003e 'sha1',\n\n        /* In some scenarios the IdP uses different certificates for\n         * signing/encryption, or is under key rollover phase and\n         * more than one certificate is published on IdP metadata.\n         * In order to handle that the toolkit offers that parameter.\n         * (when used, 'x509cert' and 'certFingerprint' values are\n         * ignored).\n         */\n        // 'x509certMulti' =\u003e array(\n        //      'signing' =\u003e array(\n        //          0 =\u003e '\u003ccert1-string\u003e',\n        //      ),\n        //      'encryption' =\u003e array(\n        //          0 =\u003e '\u003ccert2-string\u003e',\n        //      )\n        // ),\n    ),\n);\n```\nIn addition to the required settings data (IdP, SP), there is extra\ninformation that could be defined. In the same way that a template exists\nfor the basic info, there is a template for that advanced info located\nat the base folder of the toolkit and named `advanced_settings_example.php`\nthat you can copy and rename it as `advanced_settings.php`\n\n```php\n\u003c?php\n\n$advancedSettings = array(\n\n    // Compression settings\n    'compress' =\u003e array(\n        'requests' =\u003e true,\n        'responses' =\u003e true\n    ),\n    // Security settings\n    'security' =\u003e array(\n\n        /** signatures and encryptions offered */\n\n        // Indicates that the nameID of the \u003csamlp:logoutRequest\u003e sent by this SP\n        // will be encrypted.\n        'nameIdEncrypted' =\u003e false,\n\n        // Indicates whether the \u003csamlp:AuthnRequest\u003e messages sent by this SP\n        // will be signed.  [Metadata of the SP will offer this info]\n        'authnRequestsSigned' =\u003e false,\n\n        // Indicates whether the \u003csamlp:logoutRequest\u003e messages sent by this SP\n        // will be signed.\n        'logoutRequestSigned' =\u003e false,\n\n        // Indicates whether the \u003csamlp:logoutResponse\u003e messages sent by this SP\n        // will be signed.\n        'logoutResponseSigned' =\u003e false,\n\n        /* Sign the Metadata\n         False || True (use sp certs) || array(\n                                                    keyFileName =\u003e 'metadata.key',\n                                                    certFileName =\u003e 'metadata.crt'\n                                                )\n        */\n        'signMetadata' =\u003e false,\n\n        /** signatures and encryptions required **/\n\n        // Indicates a requirement for the \u003csamlp:Response\u003e, \u003csamlp:LogoutRequest\u003e\n        // and \u003csamlp:LogoutResponse\u003e elements received by this SP to be signed.\n        'wantMessagesSigned' =\u003e false,\n\n        // Indicates a requirement for the \u003csaml:Assertion\u003e elements received by\n        // this SP to be encrypted.\n        'wantAssertionsEncrypted' =\u003e false,\n\n        // Indicates a requirement for the \u003csaml:Assertion\u003e elements received by\n        // this SP to be signed. [Metadata of the SP will offer this info]\n        'wantAssertionsSigned' =\u003e false,\n\n        // Indicates a requirement for the NameID element on the SAMLResponse\n        // received by this SP to be present.\n        'wantNameId' =\u003e true,\n\n        // Indicates a requirement for the NameID received by\n        // this SP to be encrypted.\n        'wantNameIdEncrypted' =\u003e false,\n\n        // Authentication context.\n        // Set to false and no AuthContext will be sent in the AuthNRequest.\n        // 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'.\n        // 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').\n        'requestedAuthnContext' =\u003e true,\n\n        // Indicates if the SP will validate all received xmls.\n        // (In order to validate the xml, 'strict' and 'wantXMLValidation' must be true).\n        'wantXMLValidation' =\u003e true,\n\n        // If true, SAMLResponses with an empty value at its Destination\n        // attribute will not be rejected for this fact.\n        'relaxDestinationValidation' =\u003e false,\n\n        // Algorithm that the toolkit will use on signing process. Options:\n        //    'http://www.w3.org/2000/09/xmldsig#rsa-sha1'\n        //    'http://www.w3.org/2000/09/xmldsig#dsa-sha1'\n        //    'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256'\n        //    'http://www.w3.org/2001/04/xmldsig-more#rsa-sha384'\n        //    'http://www.w3.org/2001/04/xmldsig-more#rsa-sha512'\n        // Notice that rsa-sha1 is a deprecated algorithm and should not be used\n        'signatureAlgorithm' =\u003e 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256',\n\n        // Algorithm that the toolkit will use on digest process. Options:\n        //    'http://www.w3.org/2000/09/xmldsig#sha1'\n        //    'http://www.w3.org/2001/04/xmlenc#sha256'\n        //    'http://www.w3.org/2001/04/xmldsig-more#sha384'\n        //    'http://www.w3.org/2001/04/xmlenc#sha512'\n        // Notice that sha1 is a deprecated algorithm and should not be used\n        'digestAlgorithm' =\u003e 'http://www.w3.org/2001/04/xmlenc#sha256',\n\n        // ADFS URL-Encodes SAML data as lowercase, and the toolkit by default uses\n        // uppercase. Turn it True for ADFS compatibility on signature verification\n        'lowercaseUrlencoding' =\u003e false,\n    ),\n\n    // Contact information template, it is recommended to supply a\n    // technical and support contacts.\n    'contactPerson' =\u003e array(\n        'technical' =\u003e array(\n            'givenName' =\u003e '',\n            'emailAddress' =\u003e ''\n        ),\n        'support' =\u003e array(\n            'givenName' =\u003e '',\n            'emailAddress' =\u003e ''\n        ),\n    ),\n\n    // Organization information template, the info in en_US lang is\n    // recomended, add more if required.\n    'organization' =\u003e array(\n        'en-US' =\u003e array(\n            'name' =\u003e '',\n            'displayname' =\u003e '',\n            'url' =\u003e ''\n        ),\n    ),\n);\n```\n\nThe compression settings allow you to instruct whether or not the IdP can accept\ndata that has been compressed using [gzip](gzip) ('requests' and 'responses').\nBut if we provide a `$deflate` boolean parameter to the `getRequest` or `getResponse` method it will have priority over the compression settings.\n\nIn the security section, you can set the way that the SP will handle the messages\nand assertions. Contact the admin of the IdP and ask him what the IdP expects,\nand decide what validations will handle the SP and what requirements the SP will have\nand communicate them to the IdP's admin too.\n\nOnce we know what kind of data could be configured, let's talk about the way\nsettings are handled within the toolkit.\n\nThe settings files described (`settings.php` and `advanced_settings.php`) are loaded\nby the toolkit if no other array with settings info is provided in the constructor of the toolkit. Let's see some examples.\n\n```php\n// Initializes toolkit with settings.php \u0026 advanced_settings files.\n$auth = new OneLogin\\Saml2\\Auth();\n//or\n$settings = new OneLogin\\Saml2\\Settings();\n\n// Initializes toolkit with the array provided.\n$auth = new OneLogin\\Saml2\\Auth($settingsInfo);\n//or\n$settings = new OneLogin\\Saml2\\Settings($settingsInfo);\n```\n\nYou can declare the `$settingsInfo` in the file that contains the constructor\nexecution or locate them in any file and load the file in order to get the\narray available as we see in the following example:\n\n```php\n\u003c?php\n\nrequire_once 'custom_settings.php';  // The custom_settings.php contains a\n                                     // $settingsInfo array.\n\n$auth = new OneLogin\\Saml2\\Auth($settingsInfo);\n```\n\n\n#### How load the library ####\n\n\nIn order to use the toolkit library, if your project support composer you only\nneed to install it with composer (See the installation section) and you are done.\n\n\nIf your project doesn't use composer you need to import the `_toolkit_loader.php`\nfile located on the base folder of the toolkit. You can load this file in this way:\n\n```php\n\u003c?php\n\ndefine(\"TOOLKIT_PATH\", '/var/www/php-saml/');\nrequire_once(TOOLKIT_PATH . '_toolkit_loader.php');\n```\n\nAfter that line we will be able to use the classes (and their methods) of the\ntoolkit (because the external and the Saml2 libraries files are loaded).\n\nThat toolkit depends on [xmlseclibs](https://github.com/robrichards/xmlseclibs) 3.X.X branch,\nyou will need to get its code and place on your project and reuse the _toolkit_loader.php \nfile to include xmlseclibs as well.\n\n\n#### Initiate SSO ####\n\nIn order to send an `AuthNRequest` to the IdP:\n\n```php\n\u003c?php\n\ndefine(\"TOOLKIT_PATH\", '/var/www/php-saml/');\nrequire_once(TOOLKIT_PATH . '_toolkit_loader.php');   // We load the SAML2 lib\n\n$auth = new OneLogin\\Saml2\\Auth(); // Constructor of the SP, loads settings.php\n                                   // and advanced_settings.php\n$auth-\u003elogin();   // Method that sent the AuthNRequest\n```\n\nThe `AuthNRequest` will be sent signed or unsigned based on the security info\nof the `advanced_settings.php` (`'authnRequestsSigned'`).\n\n\nThe IdP will then return the SAML Response to the user's client. The client is then forwarded to the Attribute Consumer Service of the SP with this information. If we do not set a `'url'` param in the login method and we are using the default ACS provided by the toolkit (`endpoints/acs.php`), then the ACS endpoint will redirect the user to the file that launched the SSO request.\n\nWe can set a `'returnTo'` url to change the workflow and redirect the user to the other PHP file.\n\n```php\n$newTargetUrl = 'http://example.com/consume2.php';\n$auth = new OneLogin\\Saml2\\Auth();\n$auth-\u003elogin($newTargetUrl);\n```\n\nThe login method can receive other five optional parameters:\n\n* `$parameters` - An array of parameters that will be added to the `GET` in the HTTP-Redirect.\n* `$forceAuthn` - When true the `AuthNRequest` will set the `ForceAuthn='true'`\n* `$isPassive` - When true the `AuthNRequest` will set the `Ispassive='true'`\n* `$strict` - True if we want to stay (returns the url string) False to redirect\n* `$setNameIdPolicy` - When true the AuthNRequest will set a nameIdPolicy element.\n\nIf a match on the future SAMLResponse ID and the AuthNRequest ID to be sent is required, that AuthNRequest ID must to be extracted and saved.\n\n```php\n$ssoBuiltUrl = $auth-\u003elogin(null, array(), false, false, true);\n$_SESSION['AuthNRequestID'] = $auth-\u003egetLastRequestID();\nheader('Pragma: no-cache');\nheader('Cache-Control: no-cache, must-revalidate');\nheader('Location: ' . $ssoBuiltUrl);\nexit();\n```\n\n#### The SP Endpoints ####\n\nRelated to the SP there are three important views: The metadata view, the ACS view and the SLS view. The toolkit\nprovides examples of those views in the endpoints directory.\n\n##### SP Metadata `endpoints/metadata.php` #####\n\nThis code will provide the XML metadata file of our SP, based on the info that we provided in the settings files.\n\n```php\n\u003c?php\n\ndefine(\"TOOLKIT_PATH\", '/var/www/php-saml/');\nrequire_once dirname(TOOLKIT_PATH.'/_toolkit_loader.php';\n\ntry {\n    $auth = new OneLogin\\Saml2\\Auth();\n    $settings = $auth-\u003egetSettings();\n    $metadata = $settings-\u003egetSPMetadata();\n    $errors = $settings-\u003evalidateMetadata($metadata);\n    if (empty($errors)) {\n        header('Content-Type: text/xml');\n        echo $metadata;\n    } else {\n        throw new OneLogin\\Saml2\\Error(\n            'Invalid SP metadata: '.implode(', ', $errors),\n            OneLogin\\Saml2\\Error::METADATA_SP_INVALID\n        );\n    }\n} catch (Exception $e) {\n    echo $e-\u003egetMessage();\n}\n```\nThe `getSPMetadata` will return the metadata signed or not based\non the security info of the `advanced_settings.php` (`'signMetadata'`).\n\nBefore the XML metadata is exposed, a check takes place to ensure\nthat the info to be provided is valid.\n\nInstead of use the Auth object, you can directly use\n\n```php\n$settings = new OneLogin\\Saml2\\Settings($settingsInfo, true);\n```\nto get the settings object and with the true parameter we will avoid the IdP Settings validation.\n\n\n##### Attribute Consumer Service(ACS) `endpoints/acs.php` #####\n\nThis code handles the SAML response that the IdP forwards to the SP through the user's client.\n\n```php\n\u003c?php\n\nsession_start();  // IMPORTANT: This is required in order to be able\n                  // to store the user data in the session.\n\ndefine(\"TOOLKIT_PATH\", '/var/www/php-saml/');\nrequire_once dirname(TOOLKIT_PATH.'/_toolkit_loader.php';\n\n$auth = new OneLogin\\Saml2\\Auth();\n\nif (isset($_SESSION) \u0026\u0026 isset($_SESSION['AuthNRequestID'])) {\n    $requestID = $_SESSION['AuthNRequestID'];\n} else {\n    $requestID = null;\n}\n\n$auth-\u003eprocessResponse($requestID);\nunset($_SESSION['AuthNRequestID']);\n\n$errors = $auth-\u003egetErrors();\n\nif (!empty($errors)) {\n    echo '\u003cp\u003e' . implode(', ', $errors) . '\u003c/p\u003e';\n    exit();\n}\n\nif (!$auth-\u003eisAuthenticated()) {\n    echo \"\u003cp\u003eNot authenticated\u003c/p\u003e\";\n    exit();\n}\n\n$_SESSION['samlUserdata'] = $auth-\u003egetAttributes();\n$_SESSION['samlNameId'] = $auth-\u003egetNameId();\n$_SESSION['samlNameIdFormat'] = $auth-\u003egetNameIdFormat();\n$_SESSION['samlNameidNameQualifier' = $auth-\u003egetNameIdNameQualifier();\n$_SESSION['samlNameidSPNameQualifier' = $auth-\u003egetNameIdSPNameQualifier();\n$_SESSION['samlSessionIndex'] = $auth-\u003egetSessionIndex();\n\nif (isset($_POST['RelayState']) \u0026\u0026 OneLogin\\Saml2\\Utils::getSelfURL() != $_POST['RelayState']) {\n    $auth-\u003eredirectTo($_POST['RelayState']);\n}\n\n$attributes = $_SESSION['samlUserdata'];\n$nameId = $_SESSION['samlNameId'];\n\necho '\u003ch1\u003eIdentified user: '. htmlentities($nameId) .'\u003c/h1\u003e';\n\nif (!empty($attributes)) {\n    echo '\u003ch2\u003e' . _('User attributes:') . '\u003c/h2\u003e';\n    echo '\u003ctable\u003e\u003cthead\u003e\u003cth\u003e' . _('Name') . '\u003c/th\u003e\u003cth\u003e' . _('Values') . '\u003c/th\u003e\u003c/thead\u003e\u003ctbody\u003e';\n    foreach ($attributes as $attributeName =\u003e $attributeValues) {\n        echo '\u003ctr\u003e\u003ctd\u003e' . htmlentities($attributeName) . '\u003c/td\u003e\u003ctd\u003e\u003cul\u003e';\n        foreach ($attributeValues as $attributeValue) {\n            echo '\u003cli\u003e' . htmlentities($attributeValue) . '\u003c/li\u003e';\n        }\n        echo '\u003c/ul\u003e\u003c/td\u003e\u003c/tr\u003e';\n    }\n    echo '\u003c/tbody\u003e\u003c/table\u003e';\n} else {\n    echo _('No attributes found.');\n}\n```\n\nThe SAML response is processed and then checked that there are no errors.\nIt also verifies that the user is authenticated and stored the userdata in session.\n\nAt that point there are two possible alternatives:\n\n 1. If no `RelayState` is provided, we could show the user data in this view\n or however we wanted.\n\n 2. If `RelayState` is provided, a redirection takes place.\n\nNotice that we saved the user data in the session before the redirection to\nhave the user data available at the `RelayState` view.\n\n\n###### The `getAttributes` method ######\n\nIn order to retrieve attributes we can use:\n\n```php\n$attributes = $auth-\u003egetAttributes();\n```\n\nWith this method we get all the user data provided by the IdP in the Assertion\nof the SAML Response.\n\nIf we execute ```print_r($attributes)``` we could get:\n\n```php\nArray\n(\n    [cn] =\u003e Array\n        (\n            [0] =\u003e John\n        )\n    [sn] =\u003e Array\n        (\n            [0] =\u003e Doe\n        )\n    [mail] =\u003e Array\n        (\n            [0] =\u003e john.doe@example.com\n        )\n    [groups] =\u003e Array\n        (\n            [0] =\u003e users\n            [1] =\u003e members\n        )\n)\n```\n\nEach attribute name can be used as an index into `$attributes` to obtain the value. Every attribute value\nis an array - a single-valued attribute is an array of a single element.\n\n\nThe following code is equivalent:\n\n```php\n$attributes = $auth-\u003egetAttributes();\nprint_r($attributes['cn']);\n```\n\n```php\nprint_r($auth-\u003egetAttribute('cn'));\n```\n\n\nBefore trying to get an attribute, check that the user is\nauthenticated. If the user isn't authenticated or if there were\nno attributes in the SAML assertion, an empty array will be\nreturned. For example, if we call to `getAttributes` before a\n`$auth-\u003eprocessResponse`, the `getAttributes()` will return an\nempty array.\n\n\n##### Single Logout Service (SLS) `endpoints/sls.php` #####\n\nThis code handles the Logout Request and the Logout Responses.\n\n```php\n\u003c?php\n\nsession_start();  // IMPORTANT: This is required in order to be able\n                  // to close the user session.\n\ndefine(\"TOOLKIT_PATH\", '/var/www/php-saml/');\nrequire_once dirname(TOOLKIT_PATH.'/_toolkit_loader.php';\n\n$auth = new OneLogin\\Saml2\\Auth();\n\nif (isset($_SESSION) \u0026\u0026 isset($_SESSION['LogoutRequestID'])) {\n    $requestID = $_SESSION['LogoutRequestID'];\n} else {\n    $requestID = null;\n}\n\n$auth-\u003eprocessSLO(false, $requestID);\n\n$errors = $auth-\u003egetErrors();\n\nif (empty($errors)) {\n    echo 'Sucessfully logged out';\n} else {\n    echo implode(', ', $errors);\n}\n```\n\nIf the SLS endpoints receives a Logout Response, the response is\nvalidated and the session could be closed\n\n\n\n```php\n// part of the processSLO method\n\n$logoutResponse = new OneLogin\\Saml2\\LogoutResponse($this-\u003e_settings, $_GET['SAMLResponse']);\nif (!$logoutResponse-\u003eisValid($requestId)) {\n    $this-\u003e_errors[] = 'invalid_logout_response';\n} else if ($logoutResponse-\u003egetStatus() !== OneLogin\\Saml2\\Constants::STATUS_SUCCESS) {\n    $this-\u003e_errors[] = 'logout_not_success';\n} else {\n    if (!$keepLocalSession) {\n        OneLogin\\Saml2\\Utils::deleteLocalSession();\n    }\n}\n```\n\nIf the SLS endpoints receives an Logout Request, the request is validated,\nthe session is closed and a Logout Response is sent to the SLS endpoint of\nthe IdP.\n\n```php\n// part of the processSLO method\n\n$decoded = base64_decode($_GET['SAMLRequest']);\n$request = gzinflate($decoded);\nif (!OneLogin\\Saml2\\LogoutRequest::isValid($this-\u003e_settings, $request)) {\n    $this-\u003e_errors[] = 'invalid_logout_request';\n} else {\n    if (!$keepLocalSession) {\n        OneLogin\\Saml2\\Utils::deleteLocalSession();\n    }\n\n    $inResponseTo = $request-\u003eid;\n    $responseBuilder = new OneLogin\\Saml2\\LogoutResponse($this-\u003e_settings);\n    $responseBuilder-\u003ebuild($inResponseTo);\n    $logoutResponse = $responseBuilder-\u003egetResponse();\n\n    $parameters = array('SAMLResponse' =\u003e $logoutResponse);\n    if (isset($_GET['RelayState'])) {\n        $parameters['RelayState'] = $_GET['RelayState'];\n    }\n\n    $security = $this-\u003e_settings-\u003egetSecurityData();\n    if (isset($security['logoutResponseSigned']) \u0026\u0026 $security['logoutResponseSigned']) {\n        $signature = $this-\u003ebuildResponseSignature($logoutResponse, $parameters['RelayState'], $security['signatureAlgorithm']);\n        $parameters['SigAlg'] = $security['signatureAlgorithm'];\n        $parameters['Signature'] = $signature;\n    }\n\n    $this-\u003eredirectTo($this-\u003egetSLOurl(), $parameters);\n}\n```\n\nIf you aren't using the default PHP session, or otherwise need a manual\nway to destroy the session, you can pass a callback method to the\n`processSLO` method as the fourth parameter\n\n```php\n$keepLocalSession = False;\n$callback = function () {\n    // Destroy user session\n};\n\n$auth-\u003eprocessSLO($keepLocalSession, null, false, $callback);\n```\n\n\nIf we don't want that `processSLO` to destroy the session, pass a true\nparameter to the `processSLO` method\n\n```php\n$keepLocalSession = True;\n$auth-\u003eprocessSLO($keepLocalSession);\n```\n\n#### Initiate SLO ####\n\nIn order to send a Logout Request to the IdP:\n\n```php\n\u003c?php\n\ndefine(\"TOOLKIT_PATH\", '/var/www/php-saml/');\nrequire_once(TOOLKIT_PATH . '_toolkit_loader.php');\n\n$auth = new OneLogin\\Saml2\\Auth();\n\n$auth-\u003elogout();   // Method that sent the Logout Request.\n```\n\nAlso there are eight optional parameters that can be set:\n* `$returnTo` - The target URL the user should be returned to after logout.\n* `$parameters` - Extra parameters to be added to the GET.\n* `$name_id` - That will be used to build the LogoutRequest. If `name_id` parameter is not set and the auth object processed a\nSAML Response with a `NameId`, then this `NameId` will be used.\n* `$session_index` - SessionIndex that identifies the session of the user.\n* `$stay` - True if we want to stay (returns the url string) False to redirect.\n* `$nameIdFormat` - The NameID Format will be set in the LogoutRequest.\n* `$nameIdNameQualifier` - The NameID NameQualifier will be set in the LogoutRequest.\n* `$nameIdSPNameQualifier` - The NameID SP NameQualifier will be set in the LogoutRequest.\n\nThe Logout Request will be sent signed or unsigned based on the security\ninfo of the `advanced_settings.php` (`'logoutRequestSigned'`).\n\nThe IdP will return the Logout Response through the user's client to the\nSingle Logout Service of the SP.\nIf we do not set a `'url'` param in the logout method and are using the\ndefault SLS provided by the toolkit (`endpoints/sls.php`), then the SLS\nendpoint will redirect the user to the file that launched the SLO request.\n\nWe can set an `'returnTo'` url to change the workflow and redirect the user\nto other php file.\n\n```php\n$newTargetUrl = 'http://example.com/loggedOut.php';\n$auth = new OneLogin\\Saml2\\Auth();\n$auth-\u003elogout($newTargetUrl);\n```\nA more complex logout with all the parameters:\n```\n$auth = new OneLogin\\Saml2\\Auth();\n$returnTo = null;\n$paramters = array();\n$nameId = null;\n$sessionIndex = null;\n$nameIdFormat = null;\n$nameIdNameQualifier = null;\n$nameIdSPNameQualifier = null;\n\nif (isset($_SESSION['samlNameId'])) {\n    $nameId = $_SESSION['samlNameId'];\n}\nif (isset($_SESSION['samlSessionIndex'])) {\n    $sessionIndex = $_SESSION['samlSessionIndex'];\n}\nif (isset($_SESSION['samlNameIdFormat'])) {\n    $nameIdFormat = $_SESSION['samlNameIdFormat'];\n}\nif (isset($_SESSION['samlNameIdNameQualifier'])) {\n    $nameIdNameQualifier = $_SESSION['samlNameIdNameQualifier'];\n}\nif (isset($_SESSION['samlNameIdSPNameQualifier'])) {\n    $nameIdSPNameQualifier = $_SESSION['samlNameIdSPNameQualifier'];\n}\n$auth-\u003elogout($returnTo, $paramters, $nameId, $sessionIndex, false, $nameIdFormat, $nameIdNameQualifier, $nameIdSPNameQualifier);\n```\n\nIf a match on the future LogoutResponse ID and the LogoutRequest ID to be sent is required, that LogoutRequest ID must to be extracted and stored.\n\n```php\n$sloBuiltUrl = $auth-\u003elogout(null, $paramters, $nameId, $sessionIndex, true);\n$_SESSION['LogoutRequestID'] = $auth-\u003egetLastRequestID();\nheader('Pragma: no-cache');\nheader('Cache-Control: no-cache, must-revalidate');\nheader('Location: ' . $sloBuiltUrl);\nexit();\n```\n\n#### Example of a view that initiates the SSO request and handles the response (is the acs target) ####\n\nWe can code a unique file that initiates the SSO process, handle the response, get the attributes, initiate\nthe SLO and processes the logout response.\n\nNote: Review the `demo1` folder that contains that use case; in a later section we\nexplain the demo1 use case further in detail.\n\n```php\n\u003c?php\n\nsession_start();    // Initialize the session, we do that because\n                    // Note that processResponse and processSLO\n                    // methods could manipulate/close that session\n\nrequire_once dirname(__DIR__) . '/_toolkit_loader.php'; // Load Saml2 and xmlseclibs\nrequire_once 'settings.php';    // Load the setting info as an Array\n\n$auth = new OneLogin\\Saml2\\Auth($settingsInfo);  // Initialize the SP SAML instance\n\nif (isset($_GET['sso'])) {    // SSO action.  Will send an AuthNRequest to the IdP\n    $auth-\u003elogin();\n} else if (isset($_GET['sso2'])) {              // Another SSO action\n    $returnTo = $spBaseUrl.'/demo1/attrs.php';  // but set a custom RelayState URL\n    $auth-\u003elogin($returnTo);\n} else if (isset($_GET['slo'])) {  // SLO action. Will sent a Logout Request to IdP\n    $auth-\u003elogout();\n} else if (isset($_GET['acs'])) {  // Assertion Consumer Service\n    $auth-\u003eprocessResponse();      // Process the Response of the IdP, get the\n                                   // attributes and put then at\n                                   // $_SESSION['samlUserdata']\n\n    $errors = $auth-\u003egetErrors();  // This method receives an array with the errors\n                                   // that could took place during the process\n\n    if (!empty($errors)) {\n        echo '\u003cp\u003e' . implode(', ', $errors) . '\u003c/p\u003e';\n    }\n                                          // This check if the response was\n    if (!$auth-\u003eisAuthenticated()) {      // sucessfully validated and the user\n        echo '\u003cp\u003eNot authenticated\u003c/p\u003e';  // data retrieved or not\n        exit();\n    }\n\n    $_SESSION['samlUserdata'] = $auth-\u003egetAttributes(); // Retrieves user data\n    if (isset($_POST['RelayState']) \u0026\u0026 OneLogin\\Saml2\\Utils::getSelfURL() != $_POST['RelayState']) {\n        $auth-\u003eredirectTo($_POST['RelayState']);  // Redirect if there is a\n    }                                             // relayState set\n} else if (isset($_GET['sls'])) {   // Single Logout Service\n    $auth-\u003eprocessSLO();            // Process the Logout Request \u0026 Logout Response\n    $errors = $auth-\u003egetErrors(); // Retrieves possible validation errors\n    if (empty($errors)) {\n        echo '\u003cp\u003eSucessfully logged out\u003c/p\u003e';\n    } else {\n        echo '\u003cp\u003e' . implode(', ', $errors) . '\u003c/p\u003e';\n    }\n}\n\nif (isset($_SESSION['samlUserdata'])) {   // If there is user data we print it.\n    if (!empty($_SESSION['samlUserdata'])) {\n        $attributes = $_SESSION['samlUserdata'];\n        echo 'You have the following attributes:\u003cbr\u003e';\n        echo '\u003ctable\u003e\u003cthead\u003e\u003cth\u003eName\u003c/th\u003e\u003cth\u003eValues\u003c/th\u003e\u003c/thead\u003e\u003ctbody\u003e';\n        foreach ($attributes as $attributeName =\u003e $attributeValues) {\n            echo '\u003ctr\u003e\u003ctd\u003e' . htmlentities($attributeName) . '\u003c/td\u003e\u003ctd\u003e\u003cul\u003e';\n            foreach ($attributeValues as $attributeValue) {\n                echo '\u003cli\u003e' . htmlentities($attributeValue) . '\u003c/li\u003e';\n            }\n            echo '\u003c/ul\u003e\u003c/td\u003e\u003c/tr\u003e';\n        }\n        echo '\u003c/tbody\u003e\u003c/table\u003e';\n    } else {                             // If there is not user data, we notify\n        echo \"\u003cp\u003eYou don't have any attribute\u003c/p\u003e\";\n    }\n\n    echo '\u003cp\u003e\u003ca href=\"?slo\" \u003eLogout\u003c/a\u003e\u003c/p\u003e'; // Print some links with possible\n} else {                                      // actions\n    echo '\u003cp\u003e\u003ca href=\"?sso\" \u003eLogin\u003c/a\u003e\u003c/p\u003e';\n    echo '\u003cp\u003e\u003ca href=\"?sso2\" \u003eLogin and access to attrs.php page\u003c/a\u003e\u003c/p\u003e';\n}\n```\n\n#### URL-guessing methods ####\n\nphp-saml toolkit uses a bunch of methods in OneLogin\\Saml2\\Utils that try to guess the URL where the SAML messages are processed.\n\n* `getSelfHost` Returns the current host.\n* `getSelfPort` Return the port number used for the request\n* `isHTTPS` Checks if the protocol is https or http.\n* `getSelfURLhost` Returns the protocol + the current host + the port (if different than common ports).\n* `getSelfURL` Returns the URL of the current host + current view + query.\n* `getSelfURLNoQuery` Returns the URL of the current host + current view.\n* `getSelfRoutedURLNoQuery` Returns the routed URL of the current host + current view.\n\ngetSelfURLNoQuery and getSelfRoutedURLNoQuery are used to calculate the currentURL in order to valdate SAML elements like Destination or Recipient.\n\nWhen the PHP application is behind a proxy or a load balancer we can execute `setProxyVars(true)` and `setSelfPort` and `isHTTPS` will take care of the `$_SERVER[\"HTTP_X_FORWARDED_PORT\"]` and `$_SERVER['HTTP_X_FORWARDED_PROTO']` vars (otherwise they are ignored).\n\nAlso a developer can use `setSelfProtocol`, `setSelfHost`, `setSelfPort` and `getBaseURLPath` to define a specific value to be returned by `isHTTPS`, `getSelfHost`, `getSelfPort` and `getBaseURLPath`. And define a `setBasePath` to be used on the `getSelfURL` and `getSelfRoutedURLNoQuery` to replace the data extracted from `$_SERVER[\"REQUEST_URI\"]`.\n\nAt the settings the developer will be able to set a `'baseurl'` parameter that automatically will use `setBaseURL` to set values for `setSelfProtocol`, `setSelfHost`, `setSelfPort` and `setBaseURLPath`.\n\n\n### Working behind load balancer ###\n\nIs possible that asserting request URL and Destination attribute of SAML response fails when working behind load balancer with SSL offload.\n\nYou should be able to workaround this by configuring your server so that it is aware of the proxy and returns the original url when requested.\n\nOr by using the method described on the previous section.\n\n\n### SP Key rollover ###\n\nIf you plan to update the SP x509cert and privateKey you can define the new x509cert as `$settings['sp']['x509certNew']` and it will be\npublished on the SP metadata so Identity Providers can read them and get ready for rollover.\n\n\n### IdP with multiple certificates ###\n\nIn some scenarios the IdP uses different certificates for\nsigning/encryption, or is under key rollover phase and more than one certificate is published on IdP metadata.\n\nIn order to handle that the toolkit offers the `$settings['idp']['x509certMulti']` parameter.\n\nWhen that parameter is used, `'x509cert'` and `'certFingerprint'` values will be ignored by the toolkit.\n\nThe `x509certMulti` is an array with 2 keys:\n- `signing`. An array of certs that will be used to validate IdP signature\n- `encryption` An array with one unique cert that will be used to encrypt data to be sent to the IdP\n\n\n### Replay attacks ###\n\nIn order to avoid replay attacks, you can store the ID of the SAML messages already processed, to avoid processing them twice. Since the Messages expires and will be invalidated due that fact, you don't need to store those IDs longer than the time frame that you currently accepting.\n\nGet the ID of the last processed message/assertion with the `getLastMessageId`/`getLastAssertionId` methods of the Auth object.\n\n\n### Main classes and methods ###\n\nDescribed below are the main classes and methods that can be invoked.\n\n#### Saml2 library ####\n\nLets describe now the classes and methods of the SAML2 library.\n\n##### OneLogin\\Saml2\\Auth - Auth.php #####\n\nMain class of OneLogin PHP Toolkit\n\n * `Auth` - Initializes the SP SAML instance\n * `login` - Initiates the SSO process.\n * `logout` - Initiates the SLO process.\n * `processResponse` - Process the SAML Response sent by the IdP.\n * `processSLO` - Process the SAML Logout Response / Logout Request sent by the\n   IdP.\n * `redirectTo` - Redirects the user to the url past by parameter or to the url\n   that we defined in our SSO Request.\n * `isAuthenticated` - Checks if the user is authenticated or not.\n * `getAttributes` - Returns the set of SAML attributes.\n * `getAttribute` - Returns the requested SAML attribute\n * `getNameId` - Returns the nameID\n * `getNameIdFormat` - Gets the NameID Format provided by the SAML response from the IdP.\n * `getNameIdNameQualifier` - Gets the NameID NameQualifier provided from the SAML Response String.\n * `getNameIdNameSPQualifier` - Gets the NameID SP NameQualifier provided from the SAML Response String.\n * `getSessionIndex` - Gets the SessionIndex from the AuthnStatement.\n * `getErrors` - Returns if there were any error\n * `getSSOurl` - Gets the SSO url.\n * `getSLOurl` - Gets the SLO url.\n * `getLastRequestID` - The ID of the last Request SAML message generated.\n * `buildRequestSignature` - Generates the Signature for a SAML Request\n * `buildResponseSignature` - Generates the Signature for a SAML Response\n * `getSettings` - Returns the settings info\n * `setStrict` - Set the strict mode active/disable\n * `getLastRequestID` - Gets the ID of the last AuthNRequest or LogoutRequest generated by the Service Provider.\n * `getLastRequestXML` - Returns the most recently-constructed/processed XML SAML request (AuthNRequest, LogoutRequest)\n * `getLastResponseXML` - Returns the most recently-constructed/processed XML SAML response (SAMLResponse, LogoutResponse). If the SAMLResponse had an encrypted assertion, decrypts it.\n\n\n##### OneLogin\\Saml2\\AuthnRequest - `AuthnRequest.php` #####\n\nSAML 2 Authentication Request class\n\n * `AuthnRequest` - Constructs the `AuthnRequest` object.\n * `getRequest` - Returns deflated, base64 encoded, unsigned `AuthnRequest`.\n * `getId` - Returns the `AuthNRequest` ID.\n * `getXML` - Returns the XML that will be sent as part of the request.\n\n##### OneLogin\\Saml2\\Response - `Response.php` #####\n\nSAML 2 Authentication Response class\n\n * `Response` - Constructs the SAML Response object.\n * `isValid` - Determines if the SAML Response is valid using the certificate.\n * `checkStatus` - Checks if the Status is success.\n * `getAudiences` - Gets the audiences.\n * `getIssuers` - Gets the Issuers (from Response and Assertion)\n * `getNameIdData` - Gets the NameID Data provided by the SAML response from the\n   IdP.\n * `getNameId` - Gets the NameID provided by the SAML response from the IdP.\n * `getNameIdFormat` - Gets the NameID Format provided by the SAML response from the IdP.\n * `getNameIdNameQualifier` - Gets the NameID NameQualifier provided from the SAML Response String.\n * `getNameIdNameSPQualifier` - Gets the NameID SP NameQualifier provided from the SAML Response String.\n * `getSessionNotOnOrAfter` - Gets the SessionNotOnOrAfter from the\n   AuthnStatement\n * `getSessionIndex` - Gets the SessionIndex from the AuthnStatement.\n * `getAttributes` - Gets the Attributes from the AttributeStatement element.\n * `validateNumAssertions` - Verifies that the document only contains a single\n   Assertion (encrypted or not).\n * `validateTimestamps` - Verifies that the document is still valid according\n   Conditions Element.\n * `getError` - After executing a validation process, if it fails, this method returns the cause\n * `getXMLDocument` - Returns the SAML Response document (If contains an encrypted assertion, decrypts it)\n\n##### OneLogin\\Saml2\\LogoutRequest - `LogoutRequest.php` #####\n\nSAML 2 Logout Request class\n\n * `LogoutRequest` - Constructs the Logout Request object.\n * `getRequest` - Returns the Logout Request defated, base64encoded, unsigned\n * `getID` - Returns the ID of the Logout Request. (If you have the object you can access to the id attribute)\n * `getNameIdData` - Gets the NameID Data of the the Logout Request.\n * `getNameId` - Gets the NameID of the Logout Request.\n * `getIssuer` - Gets the Issuer of the Logout Request.\n * `getSessionIndexes` - Gets the SessionIndexes from the Logout Request.\n * `isValid` - Checks if the Logout Request received is valid.\n * `getError` - After executing a validation process, if it fails, this method returns the cause\n * `getXML` - Returns the XML that will be sent as part of the request or that was received at the SP.\n\n##### OneLogin\\Saml2\\LogoutResponse - `LogoutResponse.php` #####\n\nSAML 2 Logout Response class\n\n * `LogoutResponse` - Constructs a Logout Response object\n   (Initialize params from settings and if provided load the Logout Response)\n * `getIssuer` - Gets the Issuer of the Logout Response.\n * `getStatus` - Gets the Status of the Logout Response.\n * `isValid` - Determines if the SAML LogoutResponse is valid\n * `build` - Generates a Logout Response object.\n * `getResponse` - Returns a Logout Response object.\n * `getError` - After executing a validation process, if it fails, this method returns the cause.\n * `getXML` - Returns the XML that will be sent as part of the response or that was received at the SP.\n\n##### OneLogin\\Saml2\\Settings - `Settings.php` #####\n\nConfiguration of the OneLogin PHP Toolkit\n\n * `Settings` -  Initializes the settings: Sets the paths of\n   the different folders and Loads settings info from settings file or\n   array/object provided\n * `checkSettings` - Checks the settings info.\n * `getBasePath` - Returns base path.\n * `getCertPath` - Returns cert path.\n * `getLibPath` - Returns lib path.\n * `getExtLibPath` - Returns external lib path.\n * `getSchemasPath` - Returns schema path.\n * `checkSPCerts` - Checks if the x509 certs of the SP exists and are valid.\n * `getSPkey` - Returns the x509 private key of the SP.\n * `getSPcert` - Returns the x509 public cert of the SP.\n * `getSPcertNew` - Returns the future x509 public cert of the SP.\n * `getIdPData` - Gets the IdP data.\n * `getSPData`Gets the SP data.\n * `getSecurityData` - Gets security data.\n * `getContacts` - Gets contact data.\n * `getOrganization` - Gets organization data.\n * `getSPMetadata` - Gets the SP metadata. The XML representation.\n * `validateMetadata` - Validates an XML SP Metadata.\n * `formatIdPCert` - Formats the IdP cert.\n * `formatSPCert` - Formats the SP cert.\n * `formatSPCertNew` - Formats the SP cert new.\n * `formatSPKey` - Formats the SP private key.\n * `getErrors` - Returns an array with the errors, the array is empty when\n   the settings is ok.\n * `getLastErrorReason` - Returns the reason of the last error\n * `getBaseURL` -  Returns the baseurl set on the settings if any.\n * `setBaseURL` - Set a baseurl value\n * `setStrict` - Activates or deactivates the strict mode.\n * `isStrict` - Returns if the 'strict' mode is active.\n * `isDebugActive` - Returns if the debug is active.\n\n##### OneLogin\\Saml2\\Metadata - `Metadata.php` #####\n\nA class that contains functionality related to the metadata of the SP\n\n* `builder` - Generates the metadata of the SP based on the settings.\n* `signmetadata` - Signs the metadata with the key/cert provided\n* `addX509KeyDescriptors` - Adds the x509 descriptors (sign/encriptation) to\n  the metadata\n\n##### OneLogin\\Saml2\\Utils - `Utils.php` #####\n\nAuxiliary class that contains several methods\n\n * `validateXML` - This function attempts to validate an XML string against\n   the specified schema.\n * `formatCert` - Returns a x509 cert (adding header \u0026 footer if required).\n * `formatPrivateKey` - returns a RSA private key (adding header \u0026 footer if required).\n * `redirect` - Executes a redirection to the provided url (or return the\n   target url).\n * `isHTTPS` - Checks if https or http.\n * `getSelfHost` - Returns the current host.\n * `getSelfURLhost` - Returns the protocol + the current host + the port\n   (if different than common ports).\n * `getSelfURLNoQuery` - Returns the URL of the current host + current view.\n * `getSelfURL` - Returns the URL of the current host + current view + query.\n * `generateUniqueID` - Generates a unique string (used for example as ID\n   for assertions).\n * `parseTime2SAML` - Converts a UNIX timestamp to SAML2 timestamp on the\n   form `yyyy-mm-ddThh:mm:ss(\\.s+)?Z`.\n * `parseSAML2Time` - Converts a SAML2 timestamp on the form\n   `yyyy-mm-ddThh:mm:ss(\\.s+)?Z` to a UNIX timestamp. The sub-second part is\n   ignored.\n * `parseDuration` - Interprets a ISO8601 duration value relative to a given\n   timestamp.\n * `getExpireTime` - Compares two dates and returns the earliest.\n * `query` - Extracts nodes from the DOMDocument.\n * `isSessionStarted` - Checks if the session is started or not.\n * `deleteLocalSession` - Deletes the local session.\n * `calculateX509Fingerprint` - Calculates the fingerprint of a x509cert.\n * `formatFingerPrint` - Formats a fingerprint.\n * `generateNameId` - Generates a `nameID`.\n * `getStatus` - Gets Status from a Response.\n * `decryptElement` - Decrypts an encrypted element.\n * `castKey` - Converts a `XMLSecurityKey` to the correct algorithm.\n * `addSign` - Adds signature key and senders certificate to an element\n   (Message or Assertion).\n * `validateSign` - Validates a signature (Message or Assertion).\n\n##### OneLogin\\Saml2\\IdPMetadataParser - `IdPMetadataParser.php` #####\n\nAuxiliary class that contains several methods to retrieve and process IdP metadata\n\n * `parseRemoteXML` - Get IdP Metadata Info from URL.\n * `parseFileXML` - Get IdP Metadata Info from File.\n * `parseXML` - Get IdP Metadata Info from XML.\n * `injectIntoSettings` - Inject metadata info into php-saml settings array.\n\n\nFor more info, look at the source code; each method is documented and details\nabout what it does and how to use it are provided. Make sure to also check the doc folder where\nHTML documentation about the classes and methods is provided for SAML and\nSAML2.\n\n\nDemos included in the toolkit\n-----------------------------\n\nThe toolkit includes three demo apps to teach how use the toolkit, take a look on it.\n\nDemos require that SP and IdP are well configured before test it.\n\n## Demo1 ##\n\n### SP setup ###\n\nThe Onelogin's PHP Toolkit allows you to provide the settings info in two ways:\n\n * Use a `settings.php` file that we should locate at the base folder of the\n   toolkit.\n * Use an array with the setting data.\n\nIn this demo we provide the data in the second way, using a setting array named\n`$settingsInfo`. This array users the `settings_example.php` included as a template\nto create the `settings.php` settings and store it in the `demo1/` folder.\nConfigure the SP part and later review the metadata of the IdP and complete the IdP info.\n\nIf you check the code of the index.php file you will see that the `settings.php`\nfile is loaded in order to get the `$settingsInfo` var to be used in order to initialize\nthe `Setting` class.\n\nNotice that in this demo, the `setting.php` file that could be defined at the base\nfolder of the toolkit is ignored and the libs are loaded using the\n`_toolkit_loader.php` located at the base folder of the toolkit.\n\n\n### IdP setup ###\n\nOnce the SP is configured, the metadata of the SP is published at the\n`metadata.php` file. Configure the IdP based on that information.\n\n\n### How it works ###\n\n 1. First time you access to `index.php` view, you can select to login and return\n    to the same view or login and be redirected to the `attrs.php` view.\n\n 2. When you click:\n\n    2.1 in the first link, we access to (`index.php?sso`) an `AuthNRequest`\n    is sent to the IdP, we authenticate at the IdP and then a Response is sent\n    through the user's client to the SP, specifically the Assertion Consumer Service view: `index.php?acs`.\n    Notice that a `RelayState` parameter is set to the url that initiated the\n    process, the `index.php` view.\n\n    2.2 in the second link we access to (`attrs.php`) have the same process\n    described at 2.1 with the diference that as `RelayState` is set the `attrs.php`.\n\n 3. The SAML Response is processed in the ACS (`index.php?acs`), if the Response\n    is not valid, the process stops here and a message is shown. Otherwise we\n    are redirected to the RelayState view. a) `index.php` or b) `attrs.php`.\n\n 4. We are logged in the app and the user attributes are showed.\n    At this point, we can test the single log out functionality.\n\n 5. The single log out functionality could be tested by two ways.\n\n    5.1 SLO Initiated by SP. Click on the \"logout\" link at the SP, after that a\n    Logout Request is sent to the IdP, the session at the IdP is closed and\n    replies through the client to the SP with a Logout Response (sent to the\n    Single Logout Service endpoint). The SLS endpoint (`index.php?sls`) of the SP\n    process the Logout Response and if is valid, close the user session of the\n    local app. Notice that the SLO Workflow starts and ends at the SP.\n\n    5.2 SLO Initiated by IdP. In this case, the action takes place on the IdP\n    side, the logout process is initiated at the idP, sends a Logout\n    Request to the SP (SLS endpoint, `index.php?sls`). The SLS endpoint of the SP\n    process the Logout Request and if is valid, close the session of the user\n    at the local app and send a Logout Response to the IdP (to the SLS endpoint\n    of the IdP). The IdP receives the Logout Response, process it and close the\n    session at of the IdP. Notice that the SLO Workflow starts and ends at the IdP.\n\nNotice that all the SAML Requests and Responses are handled by a unique file,\nthe `index.php` file and how `GET` paramters are used to know the action that\nmust be done.\n\n\n## Demo2 ##\n\n### SP setup ###\n\nThe Onelogin's PHP Toolkit allows you to provide the settings info in two ways:\n\n * Use a `settings.php` file that we should locate at the base folder of the\n   toolkit.\n * Use an array with the setting data.\n\nThe first is the case of the demo2 app. The `setting.php` file and the\n`setting_extended.php` file should be defined at the base folder of the toolkit.\nReview the `setting_example.php` and the `advanced_settings_example.php` to\nlearn how to build them.\n\nIn this case as Attribute Consume Service and Single Logout Service we are going to\nuse the files located in the endpoint folder (`acs.php` and `sls.php`).\n\n\n### IdP setup ###\n\nOnce the SP is configured, the metadata of the SP is published at the\n`metadata.php` file. Based on that info, configure the IdP.\n\n\n### How it works ###\n\nAt demo1, we saw how all the SAML Request and Responses were handler at an\nunique file, the `index.php` file. This demo1 uses high-level programming.\n\nAt demo2, we have several views: `index.php`, `sso.php`, `slo.php`, `consume.php`\nand `metadata.php`. As we said, we will use the endpoints that are defined\nin the toolkit (`acs.php`, `sls.php` of the endpoints folder). This demo2 uses\nlow-level programming.\n\nNotice that the SSO action can be initiated at `index.php` or `sso.php`.\n\nThe SAML workflow that take place is similar that the workflow defined in the\ndemo1, only changes the targets.\n\n 1. When you access `index.php` or `sso.php` for the first time, an `AuthNRequest` is\n    sent to the IdP automatically, (as `RelayState` is sent the origin url).\n    We authenticate at the IdP and then a `Response` is sent to the SP, to the\n    ACS endpoint, in this case `acs.php` of the endpoints folder.\n\n 2. The SAML Response is processed in the ACS, if the `Response` is not valid,\n    the process stops here and a message is shown. Otherwise we are redirected\n    to the `RelayState` view (`sso.php` or `index.php`). The `sso.php` detects if the\n    user is logged and redirects to `index.php`, so we will be in the\n    `index.php` at the end.\n\n 3. We are logged into the app and the user attributes (if any) are shown.\n    At this point, we can test the single log out functionality.\n\n 4. The single log out functionality could be tested by two ways.\n\n    4.1 SLO Initiated by SP. Click on the \"logout\" link at the SP, after that\n    we are redirected to the `slo.php` view and there a Logout Request is sent\n    to the IdP, the session at the IdP is closed and replies to the SP a\n    Logout Response (sent to the Single Logout Service endpoint). In this case\n    The SLS endpoint of the SP process the Logout Response and if is\n    valid, close the user session of the local app. Notice that the SLO\n    Workflow starts and ends at the SP.\n\n    4.2 SLO Initiated by IdP. In this case, the action takes place on the IdP\n    side, the logout process is initiated at the idP, sends a Logout\n    Request to the SP (SLS endpoint `sls.php` of the endpoint folder).\n    The SLS endpoint of the SP process the Logout Request and if is valid,\n    close the session of the user at the local app and sends a Logout Response\n    to the IdP (to the SLS endpoint of the IdP).The IdP receives the Logout\n    Response, process it and close the session at of the IdP. Notice that the\n    SLO Workflow starts and ends at the IdP.\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fiwouldrathercode%2Fphp-custom-one-login","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fiwouldrathercode%2Fphp-custom-one-login","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fiwouldrathercode%2Fphp-custom-one-login/lists"}