1. Go to this page and download the library: Download karolornoch/php-saml library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
karolornoch / php-saml example snippets
$settings = array (
// If 'strict' is True, then the PHP Toolkit will reject unsigned
// or unencrypted messages if it expects them to be signed or encrypted.
// Also it will reject the messages if the SAML standard is not strictly
// followed: Destination, NameId, Conditions ... are validated too.
'strict' => true,
// Enable debug mode (to print errors).
'debug' => false,
// Set a BaseURL to be used instead of try to guess
// the BaseURL of the view that process the SAML Message.
// Ex http://sp.example.com/
// http://example.com/sp/
'baseurl' => null,
// Service Provider Data that we are deploying.
'sp' => array (
// Identifier of the SP entity (must be a URI)
'entityId' => '',
// Specifies info about where and how the <AuthnResponse> message MUST be
// returned to the requester, in this case our SP.
'assertionConsumerService' => array (
// URL Location where the <Response> from the IdP will be returned
'url' => '',
// SAML protocol binding to be used when returning the <Response>
// message. SAML Toolkit supports this endpoint for the
// HTTP-POST binding only.
'binding' => 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST',
),
// If you need to specify requested attributes, set a
// attributeConsumingService. nameFormat, attributeValue and
// friendlyName can be omitted
"attributeConsumingService"=> array(
"serviceName" => "SP test",
"serviceDescription" => "Test Service",
"requestedAttributes" => array(
array(
"name" => "",
"isRequired" => false,
"nameFormat" => "",
"friendlyName" => "",
"attributeValue" => array()
)
)
),
// Specifies info about where and how the <Logout Response> message MUST be
// returned to the requester, in this case our SP.
'singleLogoutService' => array (
// URL Location where the <Response> from the IdP will be returned
'url' => '',
// SAML protocol binding to be used when returning the <Response>
// message. SAML Toolkit supports the HTTP-Redirect binding
// only for this endpoint.
'binding' => 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect',
),
// Specifies the constraints on the name identifier to be used to
// represent the requested subject.
// Take a look on lib/Saml2/Constants.php to see the NameIdFormat supported.
'NameIDFormat' => 'urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress',
// Usually x509cert and privateKey of the SP are provided by files placed at
// the certs folder. But we can also provide them with the following parameters
'x509cert' => '',
'privateKey' => '',
/*
* Key rollover
* If you plan to update the SP x509cert and privateKey
* you can define here the new x509cert and it will be
* published on the SP metadata so Identity Providers can
* read them and get ready for rollover.
*/
// 'x509certNew' => '',
),
// Identity Provider Data that we want connected with our SP.
'idp' => array (
// Identifier of the IdP entity (must be a URI)
'entityId' => '',
// SSO endpoint info of the IdP. (Authentication Request protocol)
'singleSignOnService' => array (
// URL Target of the IdP where the Authentication Request Message
// will be sent.
'url' => '',
// SAML protocol binding to be used when returning the <Response>
// message. SAML Toolkit supports the HTTP-Redirect binding
// only for this endpoint.
'binding' => 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect',
),
// SLO endpoint info of the IdP.
'singleLogoutService' => array (
// URL Location of the IdP where SLO Request will be sent.
'url' => '',
// URL location of the IdP where the SP will send the SLO Response (ResponseLocation)
// if not set, url for the SLO Request will be used
'responseUrl' => '',
// SAML protocol binding to be used when returning the <Response>
// message. SAML Toolkit supports the HTTP-Redirect binding
// only for this endpoint.
'binding' => 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect',
),
// Public x509 certificate of the IdP
'x509cert' => '',
/*
* Instead of use the whole x509cert you can use a fingerprint in order to
* validate a SAMLResponse, but we don't recommend to use that
* method on production since is exploitable by a collision attack.
* (openssl x509 -noout -fingerprint -in "idp.crt" to generate it,
* or add for example the -sha256 , -sha384 or -sha512 parameter)
*
* If a fingerprint is provided, then the certFingerprintAlgorithm is
$advancedSettings = array (
// Compression settings
'compress' => array (
'requests' => true,
'responses' => true
),
// Security settings
'security' => array (
/** signatures and encryptions offered */
// Indicates that the nameID of the <samlp:logoutRequest> sent by this SP
// will be encrypted.
'nameIdEncrypted' => false,
// Indicates whether the <samlp:AuthnRequest> messages sent by this SP
// will be signed. [Metadata of the SP will offer this info]
'authnRequestsSigned' => false,
// Indicates whether the <samlp:logoutRequest> messages sent by this SP
// will be signed.
'logoutRequestSigned' => false,
// Indicates whether the <samlp:logoutResponse> messages sent by this SP
// will be signed.
'logoutResponseSigned' => false,
/* Sign the Metadata
False || True (use sp certs) || array (
keyFileName => 'metadata.key',
certFileName => 'metadata.crt'
)
|| array (
'x509cert' => '',
'privateKey' => ''
)
*/
'signMetadata' => false,
/** signatures and encryptions antXMLValidation' => true,
// If true, SAMLResponses with an empty value at its Destination
// attribute will not be rejected for this fact.
'relaxDestinationValidation' => false,
// If true, the toolkit will not raised an error when the Statement Element
// contain atribute elements with name duplicated
'allowRepeatAttributeName' => false,
// If true, Destination URL should strictly match to the address to
// which the response has been sent.
// Notice that if 'relaxDestinationValidation' is true an empty Destintation
// will be accepted.
'destinationStrictlyMatches' => false,
// If true, SAMLResponses with an InResponseTo value will be rejectd if not
// AuthNRequest ID provided to the validation method.
'rejectUnsolicitedResponsesWithInResponseTo' => false,
// Algorithm that the toolkit will use on signing process. Options:
// 'http://www.w3.org/2000/09/xmldsig#rsa-sha1'
// 'http://www.w3.org/2000/09/xmldsig#dsa-sha1'
// 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256'
// 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha384'
// 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha512'
// Notice that sha1 is a deprecated algorithm and should not be used
'signatureAlgorithm' => 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256',
// Algorithm that the toolkit will use on digest process. Options:
// 'http://www.w3.org/2000/09/xmldsig#sha1'
// 'http://www.w3.org/2001/04/xmlenc#sha256'
// 'http://www.w3.org/2001/04/xmldsig-more#sha384'
// 'http://www.w3.org/2001/04/xmlenc#sha512'
// Notice that sha1 is a deprecated algorithm and should not be used
'digestAlgorithm' => 'http://www.w3.org/2001/04/xmlenc#sha256',
// ADFS URL-Encodes SAML data as lowercase, and the toolkit by default uses
// uppercase. Turn it True for ADFS compatibility on signature verification
'lowercaseUrlencoding' => false,
),
// Contact information template, it is recommended to supply a
// technical and support contacts.
'contactPerson' => array (
'technical' => array (
'givenName' => '',
'emailAddress' => ''
),
'support' => array (
'givenName' => '',
'emailAddress' => ''
),
),
// Organization information template, the info in en_US lang is
// recomended, add more if
// Initializes toolkit with settings.php & advanced_settings files.
$auth = new OneLogin_Saml2_Auth();
//or
$settings = new OneLogin_Saml2_Settings();
// Initializes toolkit with the array provided.
$auth = new OneLogin_Saml2_Auth($settingsInfo);
//or
$settings = new OneLogin_Saml2_Settings($settingsInfo);
// $settingsInfo array.
$auth = new OneLogin_Saml2_Auth($settingsInfo);
define("TOOLKIT_PATH", '/var/www/php-saml/');
define("TOOLKIT_PATH", '/var/www/php-saml/');
f the SP, loads settings.php
// and advanced_settings.php
$auth->login(); // Method that sent the AuthNRequest
$newTargetUrl = 'http://example.com/consume2.php';
$auth = new OneLogin_Saml2_Auth();
$auth->login($newTargetUrl);
session_start(); // Initialize the session, we do that because
// Note that processResponse and processSLO
// methods could manipulate/close that session
l send an AuthNRequest to the IdP
$auth->login();
} else if (isset($_GET['sso2'])) { // Another SSO action
$returnTo = $spBaseUrl.'/demo1/attrs.php'; // but set a custom RelayState URL
$auth->login($returnTo);
} else if (isset($_GET['slo'])) { // SLO action. Will sent a Logout Request to IdP
$auth->logout();
} else if (isset($_GET['acs'])) { // Assertion Consumer Service
$auth->processResponse(); // Process the Response of the IdP, get the
// attributes and put then at
// $_SESSION['samlUserdata']
$errors = $auth->getErrors(); // This method receives an array with the errors
// that could took place during the process
if (!empty($errors)) {
echo '<p>', implode(', ', $errors), '</p>';
}
// This check if the response was
if (!$auth->isAuthenticated()) { // sucessfully validated and the user
echo "<p>Not authenticated</p>"; // data retrieved or not
exit();
}
$_SESSION['samlUserdata'] = $auth->getAttributes(); // Retrieves user data
if (isset($_POST['RelayState']) && OneLogin_Saml2_Utils::getSelfURL() != $_POST['RelayState']) {
// To avoid 'Open Redirect' attacks, before execute the
// redirection confirm the value of $_POST['RelayState'] is a // trusted URL.
$auth->redirectTo($_POST['RelayState']); // Redirect if there is a
} // relayState set
} else if (isset($_GET['sls'])) { // Single Logout Service
$auth->processSLO(); // Process the Logout Request & Logout Response
$errors = $auth->getErrors(); // Retrieves possible validation errors
if (empty($errors)) {
echo '<p>Sucessfully logged out</p>';
} else {
echo '<p>', implode(', ', $errors), '</p>';
}
}
if (isset($_SESSION['samlUserdata'])) { // If there is user data we print it.
if (!empty($_SESSION['samlUserdata'])) {
$attributes = $_SESSION['samlUserdata'];
echo 'You have the following attributes:<br>';
echo '<table><thead><th>Name</th><th>Values</th></thead><tbody>';
foreach ($attributes as $attributeName => $attributeValues) {
echo '<tr><td>' . htmlentities($attributeName) . '</td><td><ul>';
foreach ($attributeValues as $attributeValue) {
echo '<li>' . htmlentities($attributeValue) . '</li>';
}
echo '</ul></td></tr>';
}
echo '</tbody></table>';
} else { // If there is not user data, we notify
echo "<p>You don't have any attribute</p>";
}
echo '<p><a href="?slo" >Logout</a></p>'; // Print some links with possible
} else { // actions
echo '<p><a href="?sso" >Login</a></p>';
echo '<p><a href="?sso2" >Login and access to attrs.php page</a></p>';
}
ion_start();
$needsAuth = empty($_SESSION['samlUserdata']);
if ($needsAuth) {
// put SAML settings into an array to avoid placing files in the
// composer vendor/ directories
$samlsettings = array(/*...config goes here...*/);
$auth = new \OneLogin\Saml2\Auth($samlsettings);
if (!empty($_REQUEST['SAMLResponse']) && !empty($_REQUEST['RelayState'])) {
$auth->processResponse(null);
$errors = $auth->getErrors();
if (empty($errors)) {
// user has authenticated successfully
$needsAuth = false;
$_SESSION['samlUserdata'] = $auth->getAttributes();
}
}
if ($needsAuth) {
$auth->login();
}
}
// rest of your app goes here