{"id":13649986,"url":"https://github.com/italia/spid-php-lib","last_synced_at":"2026-01-11T16:36:16.232Z","repository":{"id":50481278,"uuid":"145509163","full_name":"italia/spid-php-lib","owner":"italia","description":"PHP package for SPID authentication","archived":false,"fork":false,"pushed_at":"2024-04-22T14:57:51.000Z","size":944,"stargazers_count":29,"open_issues_count":38,"forks_count":37,"subscribers_count":13,"default_branch":"master","last_synced_at":"2025-04-20T11:54:41.904Z","etag":null,"topics":["php","spid"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-3-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/italia.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-08-21T05:05:19.000Z","updated_at":"2023-09-23T07:53:42.000Z","dependencies_parsed_at":"2024-06-19T00:22:39.456Z","dependency_job_id":"7e811aaa-1252-47dd-93bb-1ae5d98bc1ac","html_url":"https://github.com/italia/spid-php-lib","commit_stats":null,"previous_names":[],"tags_count":12,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/italia%2Fspid-php-lib","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/italia%2Fspid-php-lib/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/italia%2Fspid-php-lib/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/italia%2Fspid-php-lib/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/italia","download_url":"https://codeload.github.com/italia/spid-php-lib/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250297139,"owners_count":21407156,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","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":["php","spid"],"created_at":"2024-08-02T02:00:32.129Z","updated_at":"2026-01-11T16:36:16.186Z","avatar_url":"https://github.com/italia.png","language":"PHP","funding_links":[],"categories":["🎭 SPID"],"sub_categories":[],"readme":"\u003cimg src=\"https://github.com/italia/spid-graphics/blob/master/spid-logos/spid-logo-b-lb.png\" alt=\"SPID\" data-canonical-src=\"https://github.com/italia/spid-graphics/blob/master/spid-logos/spid-logo-b-lb.png\" width=\"500\" height=\"98\" /\u003e\n\n[![Join the #spid-php channel](https://img.shields.io/badge/Slack%20channel-%23spid--php-blue.svg?logo=slack)](https://developersitalia.slack.com/messages/CB6DCK274)\n[![Get invited](https://slack.developers.italia.it/badge.svg)](https://slack.developers.italia.it/)\n[![SPID on forum.italia.it](https://img.shields.io/badge/Forum-SPID-blue.svg)](https://forum.italia.it/c/spid)\n[![Build Status](https://travis-ci.org/italia/spid-php-lib.svg?branch=master)](https://travis-ci.org/italia/spid-php-lib)\n\n\u003e  **CURRENT VERSION: v0.35**\n\n# spid-php-lib\nPHP package for SPID authentication.\n\nThis PHP package is aimed at implementing SPID **Service Providers**. [SPID](https://www.spid.gov.it/) is the Italian digital identity system, which enables citizens to access all public services with a single set of credentials. This package provides a layer of abstraction over the SAML protocol by exposing just the subset required in order to implement SPID authentication in a web application.\n\nAlternatives for PHP:\n- [spid-php](https://github.com/italia/spid-php) based on [SimpleSAMLphp](https://simplesamlphp.org/)\n- [spid-php2](https://github.com/simevo/spid-php2) based on [php-saml](https://github.com/onelogin/php-saml)\n\nFramework specific libraries and examples based on spid-php-lib:\n- [https://github.com/italia/spid-symfony-bundle](https://github.com/italia/spid-symfony-bundle)\n- [https://github.com/simevo/spid-symfony3-example](https://github.com/simevo/spid-symfony3-example)\n- [https://github.com/simevo/spid-wordpress](https://github.com/simevo/spid-wordpress)\n\nAlternatives for other languages:\n- [spid-perl](https://github.com/italia/spid-perl)\n- [spid-ruby](https://github.com/italia/spid-ruby)\n\n\n\nTable of Contents\n=================\n\n- [spid-php-lib](#spid-php-lib)\n- [Table of Contents](#table-of-contents)\n  - [Repository layout](#repository-layout)\n  - [Getting Started](#getting-started)\n    - [Prerequisites](#prerequisites)\n    - [Configuring and Installing](#configuring-and-installing)\n    - [Usage](#usage)\n      - [Performing login](#performing-login)\n      - [Performing logout](#performing-logout)\n      - [Complete API](#complete-api)\n    - [Example](#example)\n      - [Demo application](#demo-application)\n  - [Features](#features)\n    - [More features](#more-features)\n  - [Troubleshooting](#troubleshooting)\n  - [Testing](#testing)\n    - [Unit tests](#unit-tests)\n    - [Linting](#linting)\n  - [Contributing](#contributing)\n  - [See also](#see-also)\n  - [Authors](#authors)\n  - [License](#license)\n\n\n## Repository layout\n\n* [bin/](bin/) auxiliary scripts\n* [example/](example/) contains a demo application\n* [src/](src/) contains the library implementation\n* [test/](test/) contains the unit tests\n\n## Getting Started\n\nTested on: amd64 Debian 9.5 (stretch, current stable) with PHP 7.0.\n\nSupports PHP 7.0, 7.1 and 7.2.\n\n### Prerequisites\n\n```sh\nsudo apt install composer make openssl php-curl php-zip php-xml\n```\n\n### Configuring and Installing\n\n\n**NOTE**: during testing, please use the test Identity Provider [spid-testenv2](https://github.com/italia/spid-testenv2).\n\n\n1. Install with composer \n\n    ```composer require italia/spid-php-lib```\n\n2. (**OPTIONAL**) Manually generate key and certificate files for your Service Provider (SP).\n\n    Example: \n    ```openssl req -x509 -nodes -sha256 -days 365 -newkey rsa:2048 -subj \"/C=IT/ST=Italy/L=Milan/O=myservice/CN=localhost\" -keyout sp.key -out sp.crt```\n\n   This step can be skipped: the library takes care of this step automatically if you declare the optional `sp_key_cert_values` key in the `settings` array. Check the example in the [Usage](#usage) section for further details.\n\n3. Download the Identity Provider (IdP) metadata files and place them in a directory in your project, for example `idp_metadata`. \n    A convenience tool is provided to download those of the production IdPs: [vendor/italia/spid-php-lib/bin/download_idp_metadata.php](bin/download_idp_metadata.php), example usage:\n    ```sh\n    mkdir idp_metadata\n    php vendor/italia/spid-php-lib/bin/download_idp_metadata.php ./idp_metadata\n    ```\n\n    *TEST ENVIRONMENT: If you are using [spid-testenv2](https://github.com/italia/spid-testenv2), manually download the IdP metadata and place it in your `idp_metadata` folder*\n\n4. Make your SP known to IdPs: for production follow the guidelines at [https://www.spid.gov.it/come-diventare-fornitore-di-servizi-pubblici-e-privati-con-spid](https://www.spid.gov.it/come-diventare-fornitore-di-servizi-pubblici-e-privati-con-spid)\n\n    *TEST ENVIRONMENT: simply download your Service Provider (SP) metadata and place it in the appropriate folder of the [test environment](https://github.com/italia/spid-testenv2). The test environment must be restarted after every change to the SP metadata.*\n\n\n\n### Usage\n\nAll classes provided by this package reside in the `Italia\\Spid` namespace.\nMore detailed documentation is available in the [SAMLInterface.php](/src/Spid/Interfaces/SAMLInterface.php) file.\n\nLoad them using the composer-generated autoloader:\n```php\nrequire_once(__DIR__ . \"/vendor/autoload.php\");\n```\n\nThe main class is `Italia\\Spid\\Sp` (service provider).\n\nGenerate a settings array following this guideline\n\n```php\n$settings = array(\n    'sp_entityid' =\u003e SP_BASE_URL, // preferred: https protocol, no trailing slash, example: https://sp.example.com/\n    'sp_key_file' =\u003e '/path/to/sp.key',\n    'sp_cert_file' =\u003e '/path/to/sp.crt',\n    'sp_comparison' =\u003e 'exact', // one of: \"exact\", \"minimum\", \"better\" or \"maximum\"\n    'sp_assertionconsumerservice' =\u003e [\n        // order is important ! the 0-base index in this array will be used as ID in the calls\n        SP_BASE_URL . '/acs',\n        ...\n    ],\n    'sp_singlelogoutservice' =\u003e [\n        // order is important ! the 0-base index in this array will be used as ID in the calls\n        [SP_BASE_URL . '/slo', 'POST'],\n        [SP_BASE_URL . '/slo', 'REDIRECT']\n        ...\n    ],\n    'sp_org_name' =\u003e 'your organization full name',\n    'sp_org_display_name' =\u003e 'your organization display name',\n    'sp_key_cert_values' =\u003e [ // Optional: remove this if you want to generate .key \u0026 .crt files manually\n        'countryName' =\u003e 'Your Country',\n        'stateOrProvinceName' =\u003e 'Your Province or State',\n        'localityName' =\u003e 'Locality',\n        'commonName' =\u003e 'Name',\n        'emailAddress' =\u003e 'your@email.com',\n    ]\n    'idp_metadata_folder' =\u003e '/path/to/idp_metadata/',\n    'sp_attributeconsumingservice' =\u003e [\n        // order is important ! the 0-base index in this array will be used as ID in the calls\n        [\"fiscalNumber\"],\n        [\"name\", \"familyName\", \"fiscalNumber\", \"email\", \"spidCode\"],\n        ...\n    ],\n    // Time in seconds of skew that is acceptable between client and server when checking OnBefore and NotOnOrAfter\n    // assertion condition validity timestamps, and IssueInstant response / assertion timestamps. Optional.\n    // Default is 0. Acceptable range: 0-300 (inclusive)\n    'accepted_clock_skew_seconds' =\u003e 100\n);\n```\n\nthen initialize the main Sp class\n\n```php\n$sp = new Italia\\Spid\\Sp($settings);\n```\n\n\u003e*Don't want the library to generate .key and .crt files for you? Then remove the `sp_key_cert_values` key from the `settings` array, or decalre* \n\n```php\n// $autoconfiguration skips .key/.crt generation if set to false\n$sp = new Italia\\Spid\\Sp($settings, null, $autoconfiguration = false);\n```\n\n#### Performing login\n\n\n```php\n// shortname of IdP, same as the name of corresponding IdP metadata file, without .xml\n$idpName = 'testenv';\n// index of assertion consumer service as per the SP metadata (sp_assertionconsumerservice in settings array)\n$assertId = 0;\n// index of attribute consuming service as per the SP metadata (sp_attributeconsumingservice in settings array)\n$attrId = 1;\n\n// Generate the login URL and redirect to the IdP login page\n$sp-\u003elogin($idpName, $assertId, $attrId);\n```\nComplete the login operation by calling\n```php\n$sp-\u003eisAuthenticated();\n```\nat the assertion consumer service URL. \n\nThen call\n```php\n$userAttributes = $sp-\u003egetAttributes();\n```\nto receive an array of the requested user attributes.\n\n#### Performing logout\n\nCall\n```php\n// index of single logout service as per the SP metadata (sp_singlelogoutservice in settings array)\n$sloId = 0;\n\n$sp-\u003elogout($sloId);\n```\nThe method will redirect to the IdP Single Logout page, or return false if you are not logged in.\n\n#### Complete API\n\n|**Method**|**Description**|\n|:---|:---|\n|\\__contruct($settings, $protocol = null, $autoconfigure = true)|`$settings` should be based on the example provided in the [Usage](#usage) section. `$protocol` represents the protocol used for login. At the moment only `SAML` is supported, and can be selected by either `$protocol = 'saml'` or the default `$protocol = null`. `$autoconfigure` tells the constructor if it should check for .key and .crt files at the specified location from the `$settings` array and generate them in case they are not found. Set this to `false` if you wish to generate those manually.|\n|loadIdpFromFile(string $filename)|loads an `Idp` object by parsing the provided XML at `$filename`|\n|getIdpList() : array|loads all the `Idp` objects from the `idp_metadata_folder` provided in settings|\n|getIdp(string $filename)|alias of `loadIdpFromFile`|\n|getSPMetadata() : string|returns the SP metadata as a string|\n|login(string $idpFilename, int $assertID, int $attrID, $level = 1, string $redirectTo = null, $shouldRedirect = true)|login with REDIRECT binding. Use `$idpFilename` to select in IdP for login by indicating the name (without extension) of an XML file in your `idp_metadata_folder`. `$assertID` and `$attrID` indicate respectively the array index of `sp_assertionconsumerservice` and `sp_attributeconsumingservice` provided in settings. Optional parameters: `$level` for SPID authentication level (1, 2 or 3), `$redirectTo` to indicate an url to redirect to after login, `$shouldRedirect` to indicate if the login function should automatically redirect to the IdP or should return the login url as a string|\n|loginPost(string $idpName, int $ass, int $attr, $level = 1, string $redirectTo = null, $shouldRedirect = true)|like login, but uses POST binding|\n|logout(int $slo, string $redirectTo = null, $shouldRedirect = true)|logout with REDIRECT binding. `$slo` indicates the array index of the `sp_singlelogoutservice` provided in settings. Optional parameters: `$redirectTo` to indicate an url to redirect to after login, `$shouldRedirect` to indicate if the login function should automatically redirect to the IdP or should return the login url as a string|\n|logoutPost(int $slo, string $redirectTo = null, $shouldRedirect = true)|like logout, but uses POST binding|\n|isAuthenticated() : bool|checks if the user is authenticated. This method **MUST** be called after login and logout to finalize the operation.|\n|getAttributes() : array|If you requested attributes with an attribute consuming service during login, this method will return them in array format|\n\n### Example\n\nA basic demo application is provided in the [example/](example/) directory of this repository.\n\n**/example and /tests folders are NOT provided with the production version from packagist, remember to require the `dev-develop` version or just clone this repository (advised)**\n\nTo try it out:\n\n1. Generate a test certificate and key pair with:\n\n   ```sh\n   openssl req -x509 -nodes -sha256 -days 365 -newkey rsa:2048 -subj \"/C=IT/ST=Italy/L=Milan/O=myservice/CN=localhost\" -keyout sp.key -out sp.crt\n   ```\n\n2. Adapt the hostname of the SP changing the `$base` variable in the `example/index.php` file; the browser you'll be testing from must be able to resolve the FQDN (the default is `https://sp.example.com`). Using HTTPS is strongly suggested.\n\n3. Configure and install the test IdP [spid-testenv2](https://github.com/italia/spid-testenv2)\n\n4. Serve the `example` dir from your preferred webserver\n\n5. Visit https://sp.example.com/metadata to get the SP metadata, then copy these over to the IdP and register the SP with the IdP\n\n6. Visit https://idp.example.com/metadata to get the IdP metadata, then save it as `example/idp_metadata/testenv.xml` to register the IdP with the SP\n\n7. Visit: https://sp.example.com and click `login`.\n\n#### Demo application\n\nA Docker-based demo application is available at [https://github.com/simevo/spid-php-lib-example](https://github.com/simevo/spid-php-lib-example).\n\n## Features\n\n- provides a **lean implementation** without relying on external SAML packages\n- **routing-agnostic**, can be integrated in any web framework / CMS\n- uses a **session** to store the authentication result and the received attributes\n- does not currently support Attribute Authority (AA)\n\n|\u003cimg src=\"https://github.com/italia/spid-graphics/blob/master/spid-logos/spid-logo-c-lb.png?raw=true\" width=\"100\" /\u003e\u003cbr /\u003e_Compliance with [SPID regulations](http://www.agid.gov.it/sites/default/files/circolari/spid-regole_tecniche_v1.pdf) (for Service Providers)_||\n|:---|:---|\n|**Metadata:**||\n|parsing of IdP XML metadata (1.2.2.4)|✓|\n|support for multiple signing certificates in IdP XML metadata (1.2.2.4)||\n|parsing of AA XML metadata (2.2.4)||\n|SP XML metadata generation (1.3.2)|✓|\n|**AuthnRequest generation (1.2.2.1):**||\n|generation of AuthnRequest XML|✓|\n|HTTP-Redirect binding|✓|\n|HTTP-POST binding|✓|\n|`AssertionConsumerServiceURL` customization|The library uses `AssertionConsumerServiceIndex` customization which is preferred|\n|`AssertionConsumerServiceIndex` customization|✓|\n|`AttributeConsumingServiceIndex` customization|✓|\n|`AuthnContextClassRef` (SPID level) customization|✓|\n|`RequestedAuthnContext/@Comparison` customization|✓|\n|`RelayState` customization (1.2.2)|✓|\n|**Response/Assertion parsing**||\n|verification of `Signature` value (if any)|✓|\n|verification of `Signature` certificate (if any) against IdP/AA metadata|✓|\n|verification of `Assertion/Signature` value|✓|\n|verification of `Assertion/Signature` certificate against IdP/AA metadata|✓|\n|verification of `SubjectConfirmationData/@Recipient`|✓|\n|verification of `SubjectConfirmationData/@NotOnOrAfter`|✓|\n|verification of `SubjectConfirmationData/@InResponseTo`|✓|\n|verification of `Issuer`|✓|\n|verification of `Assertion/Issuer`|✓|\n|verification of `Destination`|✓|\n|verification of `Conditions/@NotBefore`|✓|\n|verification of `Conditions/@NotOnOrAfter`|✓|\n|verification of `Audience`|✓|\n|parsing of Response with no `Assertion` (authentication/query failure)|✓|\n|parsing of failure `StatusCode` (Requester/Responder)|✓|\n|**Response/Assertion parsing for SSO (1.2.1, 1.2.2.2, 1.3.1):**||\n|parsing of `NameID`|✓|\n|parsing of `AuthnContextClassRef` (SPID level)|✓|\n|parsing of attributes|✓|\n|**Response/Assertion parsing for attribute query (2.2.2.2, 2.3.1):**||\n|parsing of attributes| |\n|**LogoutRequest generation (for SP-initiated logout):**||\n|generation of LogoutRequest XML|✓|\n|HTTP-Redirect binding|✓|\n|HTTP-POST binding|✓|\n|**LogoutResponse parsing (for SP-initiated logout):**||\n|parsing of LogoutResponse XML|✓|\n|verification of `Response/Signature` value (if any)|✓|\n|verification of `Response/Signature` certificate (if any) against IdP metadata|✓|\n|verification of `Issuer`|✓|\n|verification of `Destination`|✓|\n|PartialLogout detection|pending, see: [#46](https://github.com/italia/spid-php-lib/issues/46)|\n|**LogoutRequest parsing (for third-party-initiated logout):**||\n|parsing of LogoutRequest XML|✓|\n|verification of `Response/Signature` value (if any)|✓|\n|verification of `Response/Signature` certificate (if any) against IdP metadata|✓|\n|verification of `Issuer`|✓|\n|verification of `Destination`|✓|\n|parsing of `NameID`|✓|\n|**LogoutResponse generation (for third-party-initiated logout):**||\n|generation of LogoutResponse XML|✓|\n|HTTP-Redirect binding|✓|\n|HTTP-POST binding|✓|\n|PartialLogout customization|pending, see: [#46](https://github.com/italia/spid-php-lib/issues/46)|\n|**AttributeQuery generation (2.2.2.1):**||\n|generation of AttributeQuery XML| |\n|SOAP binding (client)| |\n\n### More features\n\n* [x] Generation of SPID button markup\n\n## Troubleshooting\n\nIt is advised to install a browser plugin to trace SAML messages:\n\n- Firefox:\n\n  - [SAML-tracer by Olav Morken, Jaime Perez](https://addons.mozilla.org/en-US/firefox/addon/saml-tracer/)\n  - [SAML Message Decoder by Magnus Suther](https://addons.mozilla.org/en-US/firefox/addon/saml-message-decoder-extension/)\n\n- Chrome/Chromium:\n\n  - [SAML Message Decoder by Magnus Suther](https://chrome.google.com/webstore/detail/saml-message-decoder/mpabchoaimgbdbbjjieoaeiibojelbhm)\n  - [SAML Chrome Panel by MLai](https://chrome.google.com/webstore/detail/saml-chrome-panel/paijfdbeoenhembfhkhllainmocckace)\n  - [SAML DevTools extension by stefan.rasmusson.as](https://chrome.google.com/webstore/detail/saml-devtools-extension/jndllhgbinhiiddokbeoeepbppdnhhio)\n\nIn addition, you can use the [SAML Developer Tools](https://www.samltool.com/online_tools.php) provided by onelogin to understand what is going on\n\n## Testing\n\nTo test and lint this package you must place yourself in its root directory, then follow the provided instructions.\n\nAssuming you followed the installation instructions with composer, simply do:\n\n```sh\ncd vendor/italia/spid-php-lib\n```\n\n### Unit tests\n\nInstall prerequisites with composer, generate key and certificate for the SP and download the metadata for all current production IdPs with:\n```sh\ncomposer install\nbin/download_idp_metadata.php example/idp_metadata\n```\n\nthen launch the unit tests with PHPunit:\n```sh\n./vendor/bin/phpunit --stderr --testdox tests\n```\n\n### Linting\n\nThis project complies with the [PSR-2: Coding Style Guide](https://www.php-fig.org/psr/psr-2/).\n\nMake sure you are in the package directory, then lint the code with:\n\n```\n./vendor/bin/phpcs --standard=PSR2 xxx.php\n```\n\n## Contributing\n\nFor your contributions please use the [git-flow workflow](https://danielkummer.github.io/git-flow-cheatsheet/).\n\n## See also\n\n* [SPID page](https://developers.italia.it/it/spid) on Developers Italia\n\n## Authors\n\nLorenzo Cattaneo and Paolo Greppi, simevo s.r.l.\n\n## License\n\nCopyright (c) 2018-2020, Developers Italia\n\nLicense: BSD 3-Clause, see [LICENSE](LICENSE) file.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fitalia%2Fspid-php-lib","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fitalia%2Fspid-php-lib","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fitalia%2Fspid-php-lib/lists"}