Skip to content

How to do single sign-on with PHP?

Single sign-on (SSO) allows users to authenticate once and gain access to multiple applications without having to re-enter their credentials. To implement SSO with PHP, you can use a library or framework such as SimpleSAMLphp or the PHP Security Assertion Markup Language (SAML) Toolkit. These libraries provide the necessary functionality for implementing SSO, such as creating and parsing SAML assertions and communicating with a SAML identity provider.

You will also need to set up an identity provider (IdP) that your PHP application can communicate with. The IdP is responsible for authenticating users and providing the necessary information to your application to grant access.

You can use an existing identity provider such as Okta or OneLogin, or you can set up your own using software such as OpenAM or FreeIPA.

Basic Implementation Example

The following minimal example demonstrates how to initialize and use the php-saml library for SSO. Note that SSO is a two-step flow: initiating the redirect and processing the response at the ACS endpoint.

php
use OneLogin\Saml2\Auth;
use OneLogin\Saml2\Settings;

// 1. Install via Composer: composer require onelogin/php-saml
// 2. Configure Service Provider (SP) and Identity Provider (IdP) settings
$settings = new Settings([
    'sp' => [
        'entityId' => 'https://your-app.com/saml/metadata',
        'assertionConsumerService' => [
            'url' => 'https://your-app.com/saml/acs',
            'binding' => 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST',
        ],
        // Required for production: signing and encryption certificates
        'x509cert' => '-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----',
        'privateKey' => '-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----',
    ],
    'idp' => [
        'entityId' => 'https://idp.example.com/metadata',
        'singleSignOnService' => [
            'url' => 'https://idp.example.com/sso',
        ],
        'singleLogoutService' => [
            'url' => 'https://idp.example.com/slo',
        ],
    ],
]);

$auth = new Auth($settings);

// Step 1: Initiate SSO (call this in your login route)
// $auth->login(); // Redirects user to IdP and terminates script

// Step 2: Handle SAML Response (call this in your ACS route)
$auth->processResponse();
$errors = $auth->getErrors();
if (empty($errors)) {
    $nameId = $auth->getNameId();
    $sessionIndex = $auth->getSessionIndex();
    $attributes = $auth->getAttributes(); // Extract SAML attributes for user mapping
    
    // Persist authenticated state
    $_SESSION['user'] = $nameId;
    
    // Grant access to the application
}

You can also see the following link for more information on how to implement SSO with PHP: https://github.com/onelogin/php-saml

Dual-run preview — compare with live Symfony routes.