SAML Authentication and Authorization - sonuprajapati15/Authentication-Authorization GitHub Wiki

System Design: SAML Authentication and Authorization

1. Overview

SAML (Security Assertion Markup Language) is an XML-based authentication and authorization protocol used for Single Sign-On (SSO). It allows users to log in once and access multiple applications without re-entering credentials.

🔹 Example: Logging into multiple enterprise applications (e.g., Google Workspace, AWS, Salesforce) using a single corporate identity provider (IdP).


2. Functional & Non-Functional Requirements

Functional Requirements

✅ Users can log in using a Single Sign-On (SSO) mechanism.
✅ The system must support an Identity Provider (IdP) and Service Provider (SP).
✅ Authentication requests are sent via SAML Assertions (XML-based messages).
✅ Users can access multiple applications without re-authenticating.
✅ Users can log out, and their session is invalidated across all applications.

Non-Functional Requirements

Security – Use signed and encrypted assertions, prevent replay attacks.
Scalability – Supports multiple service providers and federated identities.
Performance – Optimized SAML response handling to avoid latency.
Availability – Redundant IdP setups to ensure reliability.
Compliance – Supports GDPR, HIPAA, and enterprise security policies.


3. High-Level Design (HLD)

Architecture Components

  1. User (Employee/Customer) – Initiates login using SSO.
  2. Identity Provider (IdP) – Authenticates users and issues SAML assertions.
  3. Service Provider (SP) – Validates assertions and grants access to the application.
  4. SAML Assertions – Contains authentication and authorization details (signed XML).
  5. SSO Session Management – Manages active sessions across applications.

SAML Authentication Flow

  1. User Accesses a Service Provider (SP) – The user tries to access a protected resource.
  2. SP Redirects to IdP – The SP generates a SAML AuthnRequest and redirects the user.
  3. User Authenticates with IdP – The user enters credentials at the IdP.
  4. IdP Issues a SAML Assertion – If authentication is successful, the IdP generates a signed SAML Response.
  5. SP Validates the Assertion – The SP verifies the response signature and user details.
  6. User Gains Access – The SP grants access to the protected resource.
  7. SSO Session Maintained – The user remains logged in across multiple SPs.
  8. Logout (Single Logout – SLO) – Logging out at IdP logs the user out from all SPs.

4. Low-Level Design (LLD)

Database Schema

CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    username VARCHAR(255) UNIQUE NOT NULL,
    email VARCHAR(255) UNIQUE NOT NULL,
    password_hash TEXT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE saml_sessions ( session_id UUID PRIMARY KEY, user_id INT REFERENCES users(id) ON DELETE CASCADE, sp_entity_id VARCHAR(255) NOT NULL, expires_at TIMESTAMP NOT NULL );

API Endpoints

Method Endpoint Description
GET /sso/login Redirects user to IdP for authentication
POST /sso/callback Handles IdP response (SAML Assertion)
GET /protected Access protected resource (validates session)
POST /sso/logout Logs the user out from all sessions

6. Diagrams

Flowchart – SAML Authentication Workflow

Here is the SAML Authentication Flowchart:

SAML Authentication Flow

View or edit this diagram in Whimsical.


7. Code Implementation (Node.js + Express + SAML2)

1. Install Dependencies

npm install express passport passport-saml express-session xml2js dotenv

2. Setup Express Server with SAML Authentication

require("dotenv").config();
const express = require("express");
const session = require("express-session");
const passport = require("passport");
const SamlStrategy = require("passport-saml").Strategy;

const app = express();

// Session setup app.use(session({ secret: "saml_secret", resave: false, saveUninitialized: true })); app.use(passport.initialize()); app.use(passport.session());

// SAML Strategy Configuration passport.use( new SamlStrategy( { entryPoint: process.env.SAML_ENTRY_POINT, issuer: process.env.SAML_ISSUER, cert: process.env.SAML_CERT, // Public certificate from IdP callbackUrl: process.env.SAML_CALLBACK_URL, }, (profile, done) => done(null, profile) ) );

passport.serializeUser((user, done) => done(null, user)); passport.deserializeUser((user, done) => done(null, user));

// SAML Routes app.get("/sso/login", passport.authenticate("saml")); app.post("/sso/callback", passport.authenticate("saml", { failureRedirect: "/" }), (req, res) => { res.redirect("/profile"); });

app.get("/profile", (req, res) => { if (!req.isAuthenticated()) return res.status(401).json({ message: "Unauthorized" }); res.json({ user: req.user }); });

app.post("/sso/logout", (req, res) => { req.logout(() => res.json({ message: "Logged out from SAML session" })); });

app.listen(3000, () => console.log("Server running on port 3000"));


SAML Assertion Structure (XML Example)

<saml:Assertion xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">
    <saml:Issuer>https://idp.example.com</saml:Issuer>
    <saml:Subject>
        <saml:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress">
            [email protected]
        </saml:NameID>
    </saml:Subject>
    <saml:AttributeStatement>
        <saml:Attribute Name="Role">
            <saml:AttributeValue>Admin</saml:AttributeValue>
        </saml:Attribute>
    </saml:AttributeStatement>
</saml:Assertion>

5. Trade-offs & Scalability

Factor Trade-off
Scalability Can support multiple SPs but requires federated identity management.
Security Requires digital signatures, encryption, and proper session handling.
Performance XML-based communication is slower than JWT-based authentication.
Compliance Enterprises prefer SAML for corporate SSO and security policies.

8. Conclusion

SAML is the enterprise standard for SSO and federated identity management, widely used in corporate and government environments. It provides secure authentication but has higher complexity and overhead than OAuth 2.0 or JWT-based authentication.

⚠️ **GitHub.com Fallback** ⚠️