Phase 5: Enterprise Integration & Authentication · 60 min · Python · SAML 2.0 · XML
The Concept
SAML 2.0 architecture
SAML 2.0 involves three roles:
- IdP (Identity Provider): Azure AD, Okta, PingFederate — holds user credentials, issues assertions
- SP (Service Provider): Your AI platform — trusts the IdP, consumes assertions
- User: The person trying to access your system
The flow: User → SP (redirect to IdP) → IdP (authenticate) → IdP posts SAML assertion to SP's ACS endpoint → SP validates assertion → SP creates session.
Service provider metadata generation
# SP metadata is an XML document that tells the IdP how to communicate with your service.
# The IdP imports this metadata to configure your application.
from lxml import etree
from datetime import datetime
import base64
import hashlib
def generate_sp_metadata(
entity_id: str,
acs_url: str,
slo_url: str,
cert_pem: str,
valid_hours: int = 24 * 365,
) -> str:
"""Generate SAML 2.0 Service Provider metadata XML."""
nsmap = {
"md": "urn:oasis:names:tc:SAML:2.0:metadata",
"ds": "http://www.w3.org/2000/09/xmldsig#",
}
root = etree.Element("{%s}EntityDescriptor" % nsmap["md"], nsmap=nsmap)
root.set("entityID", entity_id)
valid_until = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
root.set("validUntil", valid_until)
# SPSSODescriptor
sp_desc = etree.SubElement(root, "{%s}SPSSODescriptor" % nsmap["md"])
sp_desc.set("protocolSupportEnumeration", "urn:oasis:names:tc:SAML:2.0:protocol")
# Key descriptor (X.509 certificate for signing/encryption)
key_desc = etree.SubElement(sp_desc, "{%s}KeyDescriptor" % nsmap["md"])
key_desc.set("use", "signing")
key_info = etree.SubElement(key_desc, "{%s}KeyInfo" % nsmap["ds"])
x509_data = etree.SubElement(key_info, "{%s}X509Data" % nsmap["ds"])
x509_cert = etree.SubElement(x509_data, "{%s}X509Certificate" % nsmap["ds"])
# Strip PEM headers and newlines
cert_clean = cert_pem.replace("-----BEGIN CERTIFICATE-----", "").replace("-----END CERTIFICATE-----", "").strip().replace("\n", "")
x509_cert.text = cert_clean
# Assertion Consumer Service endpoint
acs = etree.SubElement(sp_desc, "{%s}AssertionConsumerService" % nsmap["md"])
acs.set("Binding", "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST")
acs.set("Location", acs_url)
acs.set("index", "0")
acs.set("isDefault", "true")
# Single Logout Service endpoint
slo = etree.SubElement(sp_desc, "{%s}SingleLogoutService" % nsmap["md"])
slo.set("Binding", "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect")
slo.set("Location", slo_url)
# NameIDFormat
name_id = etree.SubElement(sp_desc, "{%s}NameIDFormat" % nsmap["md"])
name_id.text = "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"
return etree.tostring(root, pretty_print=True, xml_declaration=True, encoding="UTF-8").decode()
Processing SAML responses at the ACS endpoint
from flask import Flask, request, redirect, session
from lxml import etree
import base64
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.x509 import load_pem_x509_certificate
app = Flask(__name__)
app.secret_key = os.environ["FLASK_SECRET"]
@app.route("/saml/acs", methods=["POST"])
def assertion_consumer_service():
"""ACS endpoint: receives SAML response from IdP via HTTP-POST binding."""
saml_response_b64 = request.form.get("SAMLResponse")
if not saml_response_b64:
return "Missing SAMLResponse", 400
# Decode base64 SAML response
saml_response_xml = base64.b64decode(saml_response_b64)
root = etree.fromstring(saml_response_xml)
# Parse namespaces
ns = {
"samlp": "urn:oasis:names:tc:SAML:2.0:protocol",
"saml": "urn:oasis:names:tc:SAML:2.0:assertion",
"ds": "http://www.w3.org/2000/09/xmldsig#",
}
# Extract the assertion
assertion = root.find(".//saml:Assertion", ns)
if assertion is None:
return "No assertion in SAML response", 400
# Validate the SAML response
errors = validate_saml_response(root, assertion, ns)
if errors:
return f"SAML validation failed: {'; '.join(errors)}", 403
# Extract user attributes from the assertion
attributes = extract_attributes(assertion, ns)
name_id = assertion.find(".//saml:NameID", ns)
user_email = name_id.text if name_id is not None else attributes.get("email", [""])[0]
# Create application session
session["user"] = {
"email": user_email,
"attributes": attributes,
"authenticated_via": "saml",
}
# RelayState: where to redirect after successful auth
relay_state = request.form.get("RelayState", "/dashboard")
return redirect(relay_state)
Validating XML signatures and handling common SAML failures
def validate_saml_response(response_root, assertion, ns) -> list:
"""Validate SAML response. Returns list of error messages (empty = valid)."""
errors = []
# 1. Check response status
status = response_root.find(".//samlp:StatusCode", ns)
if status is not None and status.get("Value") != "urn:oasis:names:tc:SAML:2.0:status:Success":
errors.append(f"IdP returned non-success status: {status.get('Value')}")
return errors # No point validating further
# 2. Validate XML signature
signature = assertion.find(".//ds:Signature", ns)
if signature is None:
errors.append("Assertion is not signed — reject unsigned assertions")
else:
if not verify_xml_signature(assertion, signature, ns):
errors.append("XML signature verification failed — possible tampering")
# 3. Check timing: NotBefore and NotOnOrAfter
conditions = assertion.find(".//saml:Conditions", ns)
if conditions is not None:
now = datetime.utcnow()
not_before = conditions.get("NotBefore")
if not_before:
nb = datetime.strptime(not_before, "%Y-%m-%dT%H:%M:%SZ")
# Allow 60 seconds clock skew
if now < nb - timedelta(seconds=60):
errors.append(f"Assertion not yet valid (NotBefore: {not_before}) — check clock skew")
not_on_or_after = conditions.get("NotOnOrAfter")
if not_on_or_after:
noa = datetime.strptime(not_on_or_after, "%Y-%m-%dT%H:%M:%SZ")
if now >= noa + timedelta(seconds=60):
errors.append(f"Assertion expired (NotOnOrAfter: {not_on_or_after})")
# 4. Check audience restriction
audience_restriction = assertion.find(".//saml:AudienceRestriction", ns)
if audience_restriction is not None:
audience = audience_restriction.find("saml:Audience", ns)
if audience is not None and audience.text != EXPECTED_ENTITY_ID:
errors.append(f"Audience mismatch: expected {EXPECTED_ENTITY_ID}, got {audience.text}")
# 5. Check recipient
subject_confirmation = assertion.find(".//saml:SubjectConfirmation", ns)
if subject_confirmation is not None:
recipient = subject_confirmation.get("Recipient")
if recipient and recipient != EXPECTED_ACS_URL:
errors.append(f"Recipient mismatch: expected {EXPECTED_ACS_URL}, got {recipient}")
# 6. Check InResponseTo (prevent replay attacks)
in_response_to = response_root.get("InResponseTo")
if in_response_to:
if in_response_to not in active_saml_requests:
errors.append(f"InResponseTo mismatch — possible replay attack")
else:
active_saml_requests.remove(in_response_to)
return errors
def verify_xml_signature(assertion, signature_element, ns) -> bool:
"""Verify the XML digital signature on the SAML assertion."""
from cryptography.x509 import load_pem_x509_certificate
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import hashes
# Extract the X.509 certificate from the signature
x509_cert_el = signature_element.find(".//ds:X509Certificate", ns)
cert_b64 = x509_cert_el.text
cert_der = base64.b64decode(cert_b64)
# Load the IdP's certificate (from metadata, not from the assertion itself)
# SECURITY: Always validate against the IdP's known certificate, not the one in the response
idp_cert = load_pem_x509_certificate(IDP_CERT_PEM.encode())
public_key = idp_cert.public_key()
# Extract signature value
sig_value_el = signature_element.find(".//ds:SignatureValue", ns)
signature_value = base64.b64decode(sig_value_el.text)
# Extract signed data (the canonicalized assertion)
# In production: use xmlsec library for proper XML canonicalization (C14N)
signed_info = signature_element.find("ds:SignedInfo", ns)
c14n = etree.tostring(signed_info, method="c14n", exclusive=True)
digest = hashlib.sha256(c14n).digest()
try:
public_key.verify(
signature_value,
c14n,
padding.PKCS1v15(),
hashes.SHA256(),
)
return True
except Exception:
return False
def extract_attributes(assertion, ns) -> dict:
"""Extract user attributes from SAML assertion."""
attributes = {}
attr_statements = assertion.findall(".//saml:AttributeStatement/saml:Attribute", ns)
for attr in attr_statements:
name = attr.get("Name")
values = [v.text for v in attr.findall("saml:AttributeValue", ns)]
attributes[name] = values
return attributes
Debugging SAML with SAML tracer
# SAML Tracer is a browser extension (Firefox/Chrome) that intercepts SAML messages.
# In production debugging, you decode the base64 SAMLResponse to inspect:
def decode_saml_response_for_debugging(saml_response_b64: str) -> dict:
"""Decode a SAML response for debugging — mirrors what SAML Tracer does."""
saml_xml = base64.b64decode(saml_response_b64)
root = etree.fromstring(saml_xml)
ns = {
"samlp": "urn:oasis:names:tc:SAML:2.0:protocol",
"saml": "urn:oasis:names:tc:SAML:2.0:assertion",
}
debug_info = {
"response_id": root.get("ID"),
"in_response_to": root.get("InResponseTo"),
"destination": root.get("Destination"),
"issue_instant": root.get("IssueInstant"),
"issuer": root.find(".//saml:Issuer", ns).text if root.find(".//saml:Issuer", ns) is not None else None,
"status": root.find(".//samlp:StatusCode", ns).get("Value") if root.find(".//samlp:StatusCode", ns) is not None else None,
}
assertion = root.find(".//saml:Assertion", ns)
if assertion is not None:
debug_info["assertion_id"] = assertion.get("ID")
debug_info["assertion_issuer"] = assertion.find("saml:Issuer", ns).text
conditions = assertion.find("saml:Conditions", ns)
if conditions is not None:
debug_info["not_before"] = conditions.get("NotBefore")
debug_info["not_on_or_after"] = conditions.get("NotOnOrAfter")
audience = conditions.find(".//saml:Audience", ns)
debug_info["audience"] = audience.text if audience is not None else None
# Extract all attributes
debug_info["attributes"] = extract_attributes(assertion, ns)
return debug_info
# Common SAML failures and their fixes:
# 1. Clock skew: IdP and SP clocks differ by >60s → configure clock skew tolerance
# 2. Certificate mismatch: IdP rotated their signing cert → update SP with new cert from IdP metadata
# 3. Audience restriction: EntityID in SP metadata doesn't match Audience in assertion → fix entityID
# 4. Expired assertion: User took too long to authenticate → increase NotOnOrAfter window on IdP
# 5. Recipient mismatch: ACS URL in SP metadata doesn't match Recipient in assertion → fix ACS URL
Build
Practical application
In the lab, you'll generate SP metadata XML, implement an ACS endpoint that processes SAML responses, validate XML signatures against the IdP's certificate, handle the five most common SAML failure modes (clock skew, cert mismatch, audience restriction, expired assertion, recipient mismatch), and use the SAML Tracer debugging technique to decode and inspect real SAML assertions.
A user reports "I can't log in — it just says error." You check the SAML validation logs and see: "Assertion not yet valid (NotBefore: 2026-01-15T14:32:00Z) — check clock skew". Your server's clock reads 2026-01-15T14:28:30Z. What's happening and how do you fix it?
This is a classic clock skew problem. The IdP issued the assertion with NotBefore=14:32:00Z, but your SP's clock reads 14:28:30Z — 3.5 minutes behind. The assertion appears to be "from the future" because your server hasn't reached the NotBefore time yet. The 60-second clock skew tolerance in the validation code only covers 1 minute, but the skew is 3.5 minutes. The fix: (1) immediate: increase clock skew tolerance to 300s (5 minutes), (2) permanent: sync both servers to NTP so they agree on time. The user's browser clock is irrelevant — SAML timing is between IdP and SP. The NotOnOrAfter window is about expiration, not "not yet valid." SP metadata entityID affects audience restriction, not timing.
Step 1: Set up the lab folder
In an empty folder:
npx deventure start fde-lab-05-01
python3 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install python-dotenv
Step 2: Add your API keys
The code reads these from the environment. Put them in a .env file in the folder (and add .env to .gitignore):
These providers bill you for what you use; check each one's pricing before running anything in a loop.
Step 3: Build it
Implement a SAML 2.0 Service Provider with metadata generation, ACS endpoint, XML signature validation, and debugging for common failures.
You produce:
It should have:
- SP metadata XML generation for IdP exchange
- ACS endpoint that processes SAML responses and extracts attributes
- XML signature validation with certificate matching
- Debugging guide for common SAML failures: clock skew, certificate mismatch, audience restriction, name ID format
The lesson's sections "SAML 2.0 architecture", "Service provider metadata generation", "Processing SAML responses at the ACS endpoint" explain how.
Step 4: Run it
python saml_sp.py
It has to finish without an error. Read the output before moving on: does it show what the objective asks for?
Step 5: Check it
npx deventure verify
It checks that:
saml_sp.py exists, is not empty, is valid Pythonpython saml_sp.py finishes without an error
The first time, connect the tool to your account with a token from Settings → Command line access. When every check passes, the lab is recorded as complete.