SAML Response : How to read it?

Category:
SAML, SSO with PHP
Tags:
PHP
SSO
SAML
SAML Response
Decode SAML
Decode SAML Response
Authentik
Authentik API

Mohamed Jasir
6 months ago

Intro
SAML Response :
- A SAML Response is sent by the Identity Provider to the Service Provider and if the user succeeded in the authentication process, it contains the Assertion with the NameID / attributes of the user.
- It basically used in SSO (Single sign-on) process
- e.g. sign on with Azure, or with another server as Authentik

My Concern
Recently I was working on SSO feature using SAML provider with Authentik self hosted server.
- In that I implemented SSO with it, the user is been logged in to the website via Authentik server.
- But in Redirect URL I only get SAML Response as GET param.
- Now I need to access Authentik API which requires an access token & I get only SAML Response in the response.
- I've done many R&D but didn't found a way to generate Access Token using this SAML Response.

Reaching to the Solution
- Then I try to decode this response as it was base64 encoded.
- Decoded it with base64_decode() but it was Deflated.
- Then I found this tool to Base64 Decode + Inflate
- I got an XML response in decode.

- In that XML response I found unique username by which I could generate an API token!

The Solution

- So Now in order to decode base64 & inflate it in the code I've implemented below function :

/**
 * decode & inflate Saml Response
 * @return string | string contains xml
 */
private function decodeSamlResponse(string $samlResponse): string {
    if (!$samlResponse) {
        return '';
    }

    // decode SAML response
    $samlDecoded = base64_decode($samlResponse);
    if (!$samlDecoded) {
        return '';
    }

    // inflate decoded SAML response
    $samlXml = gzinflate($samlDecoded);
    if (!$samlXml) {
        return '';
    }

    return $samlXml;
}

- In this function I could pass SAML Response in it as parameter then in return I get string response which is XML string of encoded SAML Response.
- Now I could read XML & fetch unique username from it & create Access Token using it to Access Authentik API for the logged user.

So we could decode SAML response like this.
Hope it helps further!

DevZone
Made by developer, Made for developers