SAML Authentication and Authorization - sonuprajapati15/Authentication-Authorization GitHub Wiki
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).
✅ 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.
⚡ 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.
- User (Employee/Customer) – Initiates login using SSO.
- Identity Provider (IdP) – Authenticates users and issues SAML assertions.
- Service Provider (SP) – Validates assertions and grants access to the application.
- SAML Assertions – Contains authentication and authorization details (signed XML).
- SSO Session Management – Manages active sessions across applications.
- User Accesses a Service Provider (SP) – The user tries to access a protected resource.
- SP Redirects to IdP – The SP generates a SAML AuthnRequest and redirects the user.
- User Authenticates with IdP – The user enters credentials at the IdP.
- IdP Issues a SAML Assertion – If authentication is successful, the IdP generates a signed SAML Response.
- SP Validates the Assertion – The SP verifies the response signature and user details.
- User Gains Access – The SP grants access to the protected resource.
- SSO Session Maintained – The user remains logged in across multiple SPs.
- Logout (Single Logout – SLO) – Logging out at IdP logs the user out from all SPs.
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
);
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 |
Here is the SAML Authentication Flowchart:
View or edit this diagram in Whimsical.
npm install express passport passport-saml express-session xml2js dotenv
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 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>
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. |
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.