What is SAML and how SAML authentication works
Tags: saml, sso, tutorial, webdev
Published: 2023-04-03 20:43:22

## What is SAML

Security Assertion Markup Language (SAML) is an XML-based standard protocol for exchanging authentication data between two parties. SAML is designed to enable Single Sign- On (SSO) across different applications and systems that belong to the same organization or consortium. SAML allows a user to log in once and then access multiple applications or services without having to log in again for each application or service, this is exactly SSO.

SAML is based on the concept of a trust relationship between the identity provider (IdP) and the service provider (SP). The IdP is responsible for authenticating the user and providing the necessary identity information in the form of SAML assertions to the SP. SP uses the SAML assertions to grant or deny access to resources.

SAML is famous in enterprise environments, online service providers and government agencies. It is most popula SSO protocols. The SAML standard is maintained by the Organization for the Advancement of Structured Information Standards (OASIS), and it is continually evolving to meet the changing security and privacy requirements of modern internet based applications.

## Benefits of SAML

**Secure**: SAML allows for secure transfer of authentication and authorization data between parties and make sure that user identity and access information is confidential. SAML is designed by keeping in mind security requirement of enterprises and regulated industry, that’s why it’s highly secure protocol.

**SSO**: Using SAML organizations can implement SSO for their multiple applications means users can access multiple web applications and services without login multiple time. it solves the problems of multiple credentials for multiple applications which belongs to one organizations.
Scalability: SAML supports a wide range of authentication and authorization scenarios and use cases. This makes SAML highly scalable and adaptable to variety of business requirements. It can fit in most of the industry with it’s flexibility and security.

**Interoperability**: SAML is a popular SSO Protocol which means it can be used with different vendor’s applications and systems. It’s specificiations are well defined and give great flexibility without doing customization to it, that’s make sure that cross oganizations applications are compatible with each other.

**Save cost**: SAML reduce cost of managing user’s authnetications and access to multiple applications and services, Login once reduce processsing of number of authentications on multiple applications.

**Enhanced User Experience**: SSO always make user experience better, if organization have multiple applications and if user doesn’t require to singup as well login multiple time.
Compliance: SAML is well designed for enterprises requirements, it has all security and privacy scenerios which make it’s compliant protocol.

## SAML terminology

**Identity Provider (IdP)**: Identity Provider is authenticate users and generte SAML assertions that contain data about user identity and access related.

**Service Provider (SP)**: Service provider is application that users want to access after successfull authentication by Identity Provider. Service Provider accept SAML assertion sent by Identity Provider.

**SAML Assertion**: A SAML assertion is an XML document that contains data of user’s identity (ID and Atrributes) and access, also metadata of the assertion itself, such as its validity period, public key and the IdP that issued it.

**SAML Protocol**: A set of rules and methods for exchanging SAML assertions between the Identity provider and the Service Provider. In January 2001, OASIS Security Services Technical Committee (SSTC) convened for the first time with mandate of creating an XML framework to facilitate the exchange of authentication and authorization information.

**Attribute**: An attribute is a use profile related fields, such as name, email address, or group. It is paert of a SAML assertion. Attributes are used by the SP to identify identify user and provide access according to it.

**NameID**: A NameID is a unique identifier that is assigned to a user by the IdP and included in a SAML assertion. NameID is used by the SP to identify the user across different applications.

**Metadata**: Metadata is information about a identity Provider or Service Provider, SP require IdP’s meta data and IdP require SP’s metadata to establish trust between both. Metadata includes information about the SP or IdP’s endpoints (assertion consumer service URL, SLO URL etc.), certificate, audience and other relevant details.

**Subject**: Subject refers to user on whose behalf the SAML assertion has been generated, it contains NameID XML tag also.
Single Logout (SLO): A process that enables a user to log out of all web applications or services that use SAML authentication with a single action.

**Binding**: Method for transmitting SAML messages between an IdP and an SP, such as HTTP Redirect, HTTP POST, or SOAP.

## SAML flows
Here is The general steps of creating a SAML assertion and consumption involves the following steps:

**User Attempt to Access Restriucted Resources**: User attempts to access a service provider (SP) application that requires authentication. SP redirects the user to the Identity Provider (IDP) for authentication.

**IdP Authentication**: IdP authenticates the user in this step if user’s session doesn’t exist. IdP can authanticate using a various methods example username and password, two-factor authentication, or smart card authentication.

**Assertion Creation**: Once the user is authenticated, IdP creates a SAML assertion that contains data about user and authentication status. IdP Sign the assertion using IdP Proivate key to ensure its authenticity and integrity.

**Assertion Delivery**: IdP sends the SAML assertion to the SP via the user’s browser, using either the HTTP POST or HTTP Redirect binding. IdP Sends assertion in XML format.

**Assertion Validation**: SP receives the SAML assertion and validates it by verifying the signature, checking the expiration date, and verifying that the assertion is intended for the SP.

**Attribute Extraction**: Once the SAML assertion is validated, SP extracts user attributes such as name, email, and group.

**Session Creation**: SP creates a session for user, allowing user to access SP application. There are two types flows in SAML, these are IdP-Intiaited and SP-Initiated flows.

## IdP initiated

SAML IdP-initiated flow is a scenario where the user is first authenticated by the Identity Provider (IDP) and then redirected to a Service Provider (SP) application without the user having to initiate the request. The process involves the following steps:

**IdP Authentication**: User try to access the specific SP application, IdP authenticates the user in this step if user’s session doesn’t exist. IdP can authanticate using a various methods example username and password, two-factor authentication, or smart card authentication.

**Assertion Creation**: Once the user is authenticated, IdP creates a SAML assertion that contains data about user and authentication status. IdP Sign the assertion using IdP Proivate key to ensure its authenticity and integrity.

**Assertion Delivery**: IdP sends the SAML assertion to the SP via the user’s browser, using either the HTTP POST or HTTP Redirect binding. IdP Sends assertion in XML format.

**Assertion Validation**: SP receives the SAML assertion and validates it by verifying the signature, checking the expiration date, and verifying that the assertion is intended for the SP.

**Attribute Extraction**: Once the SAML assertion is validated, SP extracts user attributes such as name, email, and group.

**Session Creation**: SP creates a session for user, allowing user to access SP application. In the IdP-initiated flow, the user is first authenticated by IdP, and request is initiated by the IdP, which then sends SAML assertion to SP. This flow is typically used in situations where user is on IdP portal and use want to access SP directly.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hfcn4dsbjhf86jsxl3v8.png)

## SP-Intiated

SAML SP-initiated flow is a scenario where user initiates the request to access a Service Provider (SP) application and is then redirected to the Identity Provider (IDP) for authentication. The process involves the following steps:

User Attempt to Access Restriucted Resources: User attempts to access a service provider (SP) application that requires authentication.

**SP Request:** The SP determines that user needs to be authenticated and sends a SAML request to the IdP, requesting user’s authentication and authorization information,.

**SP Request validation**: IdP receives the SAML request and validate and verify by signature.

**IdP Authentication**: IdP authenticates the user in this step if user’s session doesn’t exist. IdP can authanticate using a various methods example username and password, two-factor authentication, or smart card authentication.

**Assertion Creation**: Once the user is authenticated, IdP creates a SAML assertion that contains data about user and authentication status. IdP Sign the assertion using IdP Proivate key to ensure its authenticity and integrity.

**Assertion Delivery**: IdP sends the SAML assertion to the SP via the user’s browser, using either the HTTP POST or HTTP Redirect binding. IdP Sends assertion in XML format.

**Assertion Validation**: SP receives the SAML assertion and validates it by verifying the signature, checking the expiration date, and verifying that the assertion is intended for the SP.

**Attribute Extraction**: Once the SAML assertion is validated, SP extracts user attributes such as name, email, and group.

**Session Creation**: SP creates a session for user, allowing user to access SP application. In the SP-initiated flow, the user initiates the request to access the SP application, and the SP sends a SAML request to the IDP for authentication and authorization. This flow is typically used in situations where the user needs to access a specific resource or application directly.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n8e7wmxkfpd2ass0eyty.png)

## SAML Use cases

**Workforce SSO**
SAML is very popular into Workforce SSO, All the Workforce SSO providers support SAML so it can be integrated with internal tools either SaaS or on-prem. Using workfoce SSO companies can control their employees accesses from a single dashboard, onboarding, management and offbording. As SAML is well defined protocol so it’s highly secure and flexible which fits in enterprise ecosystem for identity use case. All the enterprises and mid-sized businesses use Workforce SSO.

**B2B SaaS SSO**
When we say that all the Enterprise and mid-sized use Workforce SSO means all B2B SaaS solution who deal or want to deal in this segment means they require to integrate SAML so their customer’s Workforce SSO can be integrated with their system. All the B2B SaaS platform these days supports integration of Workforce SSO.

**Example SAML Response: **

```
<samlp:Response ID="_257f9d9e9fa14962c0803903a6ccad931245264310738"
IssueInstant="2009-06-17T18:45:10.738Z" Version="2.0">
<saml:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">
https://www.salesforce.com
</saml:Issuer>
<samlp:Status>
<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
</samlp:Status>

<saml:Assertion ID="_3c39bc0fe7b13769cab2f6f45eba801b1245264310738"
IssueInstant="2009-06-17T18:45:10.738Z" Version="2.0">
<saml:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">
https://www.salesforce.com
</saml:Issuer>
<saml:Signature>
<saml:SignedInfo>
<saml:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
<saml:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
<saml:Reference URI="#_3c39bc0fe7b13769cab2f6f45eba801b1245264310738">
<saml:Transforms>

<saml:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-
signature"/>

<saml:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#">
<ec:InclusiveNamespaces PrefixList="ds saml xs"/>
</saml:Transform>
</saml:Transforms>
<saml:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<saml:DigestValue>vzR9Hfp8d16576tEDeq/zhpmLoo=
</saml:DigestValue>
</saml:Reference>
</saml:SignedInfo>
<saml:SignatureValue>
AzID5hhJeJlG2llUDvZswNUrlrPtR7S37QYH2W+Un1n8c6kTC
Xr/lihEKPcA2PZt86eBntFBVDWTRlh/W3yUgGOqQBJMFOVbhK
M/CbLHbBUVT5TcxIqvsNvIFdjIGNkf1W0SBqRKZOJ6tzxCcLo
9dXqAyAUkqDpX5+AyltwrdCPNmncUM4dtRPjI05CL1rRaGeyX
3kkqOL8p0vjm0fazU5tCAJLbYuYgU1LivPSahWNcpvRSlCI4e
Pn2oiVDyrcc4et12inPMTc2lGIWWWWJyHOPSiXRSkEAIwQVjf
Qm5cpli44Pv8FCrdGWpEE0yXsPBvDkM9jIzwCYGG2fKaLBag==
</saml:SignatureValue>
<saml:KeyInfo>
<saml:X509Data>
<saml:X509Certificate>
MIIEATCCAumgAwIBAgIBBTANBgkqhkiG9w0BAQ0FADCBgzELM
[Certificate truncated for readability...]
</saml:X509Certificate>
</saml:X509Data>
</saml:KeyInfo>
</saml:Signature>
<saml:Subject>
<saml:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified">
saml01@salesforce.com
</saml:NameID>
<saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
<saml:SubjectConfirmationData NotOnOrAfter="2009-06-17T18:50:10.738Z"
Recipient="https://login.salesforce.com"/>
</saml:SubjectConfirmation>
</saml:Subject>
<saml:Conditions NotBefore="2009-06-17T18:45:10.738Z" NotOnOrAfter="2009-06-
17T18:50:10.738Z">
<saml:AudienceRestriction>

<saml:Audience>https://saml.salesforce.com</saml:Audience>
</saml:AudienceRestriction>
</saml:Conditions>
<saml:AuthnStatement AuthnInstant="2009-06-17T18:45:10.738Z">
<saml:AuthnContext>
<saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified
</saml:AuthnContextClassRef>
</saml:AuthnContext>
</saml:AuthnStatement>
<saml:AttributeStatement>
<saml:Attribute Name="portal_id">
<saml:AttributeValue xsi:type="xs:anyType">060D00000000SHZ
</saml:AttributeValue>
</saml:Attribute>
<saml:Attribute Name="organization_id">
<saml:AttributeValue xsi:type="xs:anyType">00DD0000000F7L5
</saml:AttributeValue>
</saml:Attribute>
<saml:Attribute Name="ssostartpage"
NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified">
<saml:AttributeValue xsi:type="xs:anyType">
http://www.salesforce.com/security/saml/saml20-gen.jsp
</saml:AttributeValue>
</saml:Attribute>
<saml:Attribute Name="logouturl"
NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri">
<saml:AttributeValue xsi:type="xs:string">
http://www.salesforce.com/security/del_auth/SsoLogoutPage.html
</saml:AttributeValue>
</saml:Attribute>
</saml:AttributeStatement>
</saml:Assertion>
</samlp:Response>
```

## Conclusion
SAML solves the Security and User experience problems with greater flexibility, it is defacto solution when we think about the identity exchange between two parties. SAML’s strength is it’s well define specification which make this fir for most of the use canse of Identity Federation and SSO. SAML is not that popular in B2C applications, JWT, OAuth and OIDC are well known protocols into B2C.