TL;DR
- Use a maintained SAML service provider implementation where possible. XML signatures, SAML profiles, metadata, and session correlation are easy to implement incorrectly.
- Verify the signature against a signing certificate obtained through trusted IdP configuration, then consume only the exact assertion node returned by signature verification.
- Validate issuer, audience, response destination, recipient, time conditions, and InResponseTo. Record assertion and request IDs with atomic one-time semantics to prevent replay.
- Prefer SP-initiated login. IdP-initiated SSO lacks the SP’s pre-login correlation state and needs additional controls, especially around replay and RelayState.
- Map the verified identity to a tenant and local account using a stable issuer and subject pair. Do not grant access merely because an assertion contains an email address or group name.
Where a SAML service provider is exposed
Security Assertion Markup Language (SAML) 2.0 lets an identity provider (IdP) send an authentication statement and attributes to a service provider (SP). A browser carries the response to the SP’s Assertion Consumer Service (ACS), commonly as an HTTP POST. The SP validates the message and creates an application session. A valid signature is necessary, but it is only one part of this decision.
The ACS accepts attacker-controlled XML and base64 input over an unauthenticated endpoint. The application must establish who signed which element, whether the response was meant for this SP, whether it belongs to a login the user just began, whether it is still valid, and whether the resulting identity should be allowed into the selected tenant. A weakness in any of those checks can turn a correctly signed assertion into the wrong authenticated session.
For new integrations, use a vetted SAML SP library that implements the Web Browser SSO profile and has an actively maintained security history. This article is a review framework for those trust boundaries, not a recipe for building XML signatures or the SAML protocol yourself.
In an SP-initiated flow, the application creates an authentication request and correlates the response to that request. In an IdP-initiated flow, the IdP sends an unsolicited response without the SP having started a matching request. OWASP notes that this removes an important layer of login-intent validation, so prefer SP initiation when the partner setup allows it. OWASP SAML Security Cheat Sheet · OASIS SAML 2.0 Profiles
Establish trust before accepting a response
Bind an IdP configuration to a tenant
Store the IdP entity ID, SSO endpoint, supported binding, signing certificates, and accepted claim mapping in a tenant-scoped identity configuration. Do not let a callback choose its own issuer URL, tenant, signing certificate, or key source from XML attributes. The configuration identifies which IdP is trusted for the tenant and which local login policy applies.
Metadata can simplify partner setup, but treat it as configuration input rather than self-authenticating truth. Fetch metadata through a controlled enrollment or refresh path, validate its origin and size, review entity and endpoint changes, and establish a key-rotation policy. Never fetch a URL named in an incoming response. A response’s KeyInfo is not a trust anchor. SignXML warns that default system CA trust is not enough to identify the intended SAML IdP; pass a certificate trusted through IdP configuration. SignXML verification documentation
Keep old and new signing keys during a planned rotation only when the IdP has documented the overlap and your policy permits it. Alert on an unknown signing certificate instead of silently trusting it. Record which configuration version verified each login so an incident review can reconstruct the decision.
Choose a stable account identity
Use an identity key such as the configured IdP issuer plus the NameID value and NameID format, or another explicitly agreed immutable identifier. Email can be renamed, reassigned, aliased, or represented with different case and normalization. Use it as a contact attribute or login hint only under a clear policy. Do not automatically merge a SAML identity into an existing local account solely because both contain the same email string.
Bind a successful federated identity to a tenant during administrator-controlled onboarding. An IdP may be valid for one customer organization but not another. A group claim also needs a tenant-specific mapping from the external group identifier to a local role. Ignore unknown groups or fail according to policy. Never accept a client-provided role or tenant ID from form fields, query parameters, or unsigned response content.
Correlate SP-initiated requests and browser sessions
When a user chooses company SSO, select the tenant’s known IdP and create a cryptographically unpredictable request ID and browser state value. Persist a short-lived pending login record keyed by the request ID, with expected IdP issuer, SP entity ID, ACS URL, tenant, browser session binding, creation time, and consumed state. Send an AuthnRequest to the configured IdP endpoint using the negotiated binding.
Bind the browser to the pending request with a short-lived secure, HTTP-only cookie or equivalent server-side session. Set the cookie policy to work with the cross-site POST behavior the integration needs, and test it in supported browsers. Apply CSRF protections to the initiation route and allowlist any post-login destination. A return URL from RelayState must never become an arbitrary redirect.
On the ACS callback, require request correlation for SP-initiated login. Match InResponseTo to a pending request that belongs to the current browser, expected IdP, tenant, and SP. Consume that record exactly once. Use a transaction and unique constraints so two concurrent copies of the response cannot both create sessions.
The protocol request ID and response assertion ID are separate replay controls. Store accepted response and assertion identifiers with expiry at least as long as the assertion’s acceptance window, and reject identifiers already seen. A cache can work only if its consistency and outage behavior meet the security contract. A partition that lets two workers accept the same identifier defeats replay protection. Define whether login fails closed when replay state cannot be written.
Validate XML safely and verify the intended signed element
Limit request size before base64 decoding and reject malformed or oversized input. Parse XML with external entity and DTD processing disabled, and use trusted local schema copies when schema validation is part of the library’s pipeline. Never download a schema location supplied by the document. XML entity controls and signature verification solve different problems: a safe parser does not establish who signed an assertion.
Use a maintained signature library and a pre-trusted IdP certificate. Configure expected signature location and algorithms according to the partner contract. Then use only the signed node returned by the verifier. SignXML calls this the “see what is signed” rule. Application code must not verify one node and then locate a different assertion by searching the document. SignXML: signature verification and expected element location · Python XML processing security notes
from signxml import XMLVerifier, SignatureConfiguration
# response_xml is bounded, decoded input.
# idp_signing_cert comes from trusted tenant configuration.
expected = SignatureConfiguration(
location="./{urn:oasis:names:tc:SAML:2.0:assertion}Assertion/"
)
verified = XMLVerifier().verify(
response_xml,
x509_cert=idp_signing_cert,
expect_config=expected,
)
signed_assertion = verified.signed_xml
This example illustrates verification against a signed Assertion child and is not a complete SP. Some partners sign the outer Response, some sign the Assertion, and some sign both. Configure the expected location to match a deliberately chosen and tested profile. If accepting either form is required, implement both branches explicitly and ensure the assertion used for authentication is covered by a trusted signature. Do not accept arbitrary unsigned assertions because another signature in the document passed.
Validate schema and protocol structure before business logic uses the XML. Use namespace-aware, exact element selection. Avoid broad searches such as “first element named Assertion” when multiple nodes may exist. Signature-wrapping attacks exploit a mismatch between the node cryptography verifies and the node application code reads. OWASP recommends local schemas and strict element selection. OWASP signature-wrapping guidance
Apply response and assertion checks
After signature verification, compare each protocol field against configured expectations. A robust profile validation includes:
- Response issuer matches the tenant’s configured IdP entity ID.
- Assertion issuer is the expected authority, and the signature policy covers the assertion consumed.
- Response Destination exactly matches the deployed ACS URL.
- Subject confirmation Recipient exactly matches the ACS URL, and bearer confirmation has a valid NotOnOrAfter.
- Audience restriction contains the SP’s entity ID. Do not treat an audience for another service as acceptable.
- InResponseTo matches the unexpired request record for SP-initiated login.
- Response and assertion time conditions are valid, with a small explicit clock-skew allowance and synchronized server clocks.
- Response and assertion IDs have not been accepted before and are recorded atomically before issuing a session.
- The assertion contains the expected authentication statement and required subject. Apply authentication-age rules if the product requires them.
These checks are not interchangeable. A valid audience does not prove the response was sent to this ACS, and a valid destination does not prove it answers a request from this browser. OASIS defines the Web Browser SSO profile and bearer subject confirmation rules, including recipient, expiry, and request correlation. OASIS SAML Profiles, Web Browser SSO
Do not loosen validation to accommodate one partner’s malformed response without documenting the exception and isolating it to that partner configuration. Capture a redacted test fixture and resolve profile mismatches with the IdP administrator. Never save live assertions or session cookies in general-purpose application logs.
Handle IdP-initiated SSO and RelayState deliberately
Some enterprise customers require IdP-initiated SSO. Because the SP has no matching request ID and pre-login browser state, there is no direct proof that the user just initiated login at the SP. This mode can create login-CSRF risk when a victim’s browser is induced to accept an attacker-controlled account session.
If the product must accept unsolicited responses, isolate that ACS policy from SP-initiated callbacks. Continue strict issuer, destination, recipient, audience, signature, expiry, tenant, and replay checks. Require tenant-specific IdP selection and do not select a customer tenant from an untrusted email domain. Map landing pages from trusted server-side tenant configuration.
Treat RelayState as opaque correlation data or a strictly validated local route token. A URL must be normalized and checked against a same-origin allowlist. Reject external hosts, protocol-relative URLs, encoded separators, and alternate host spellings. OWASP recommends explicit allowlisting for URL-valued RelayState and response or assertion replay detection. OWASP IdP-initiated SSO considerations
Turn verified claims into a narrow application session
Authentication establishes a principal; it does not automatically authorize every API action. Map only approved attributes. Validate claim types and value length, normalize identifiers under a documented rule, and reject duplicate or ambiguous attributes where a single value is required. Treat every group and role mapping as a tenant policy decision. Apply authorization again on each resource operation.
After protocol and account checks succeed, rotate the pre-authentication session identifier and create a local session with the application’s normal expiry, revocation, and audit behavior. Do not place the assertion in a browser cookie. Keep only the identity reference and authentication context needed in the session. Return a generic failure to the browser while logging a structured internal reason code that does not expose tokens or assertion contents.
Account linking should require an authenticated local session or administrator-approved workflow. A login-time “email matches, so merge” rule creates account takeover opportunities when verification policies differ between systems. For just-in-time provisioning, define tenant invitation policy, local defaults, lifecycle updates, and what happens when the IdP removes a user or group.
Keep the SAML flow and application role system separate. An assertion can prove the user authenticated with a particular IdP. A tenant-scoped mapping decides which local role applies. Review those mappings when an IdP administrator changes group names or attributes, and log mapping changes as security-sensitive configuration.
Test the protocol boundary with adversarial fixtures
Create a test matrix using signed assertions from a test IdP and controlled mutations. Include a wrong signing certificate, expired certificate, unknown issuer, altered assertion after signing, signature moved to a sibling element, multiple assertions, wrong audience, wrong destination, wrong recipient, expired and not-yet-valid conditions, missing or mismatched InResponseTo, reused IDs, malformed XML, external entity declarations, oversized payloads, and unsafe RelayState. Each invalid case must fail before a local session is created.
Exercise races, not just single requests. Send the same valid assertion simultaneously to two application workers and confirm only one can consume it. Isolate the replay store and verify its documented fail-closed behavior. Test certificate rotation during and after its planned overlap. Use synthetic identities to test each partner’s signature placement, binding, NameID format, and claim casing.
OWASP’s Web Security Testing Guide describes moving a valid signed assertion and inserting a second assertion that application code might mistakenly read. Add that parser-differential case to a library upgrade regression suite. OWASP Web Security Testing Guide: SAML authentication
Use generated test keys, synthetic users, and redacted fixtures. A production assertion can contain personal information and bearer credentials. Do not paste it into tickets, public issues, analytics events, or online XML viewers.
Frequently asked questions
Is a valid SAML XML signature enough to authenticate a user?
No. Verify the signer against the tenant’s trusted IdP configuration and use the exact signed assertion. Then check issuer, audience, destination, recipient, time conditions, request correlation, replay state, and local account policy. A signature proves integrity under a key; it does not prove the assertion is intended for this SP or login.
Should an SP accept IdP-initiated SSO?
Prefer SP-initiated SSO because the SP can bind the response to a pending request and browser state. If a customer requires unsolicited responses, isolate that policy and continue strict signature, audience, destination, expiry, tenant, and replay validation. Do not treat RelayState as an arbitrary redirect.
Can the SP trust the certificate embedded in a SAML response?
Do not let an incoming response establish its own signer trust. Load the expected signing certificate or rotation set from trusted tenant configuration. Review metadata updates through a controlled path and reject unrecognized keys until the trust policy explicitly accepts them.
Can an email address be the federated account’s permanent key?
Usually it is safer to key the federated identity by trusted issuer and a stable subject identifier. Email can change or be reassigned. Use it for contact or login discovery only under an explicit verification and account-linking policy, and never merge accounts solely because two systems return matching email strings.
Planning a SAML integration for a B2B product? Talk to Dumb Potato about SP-initiated flows, identity mapping, certificate rotation, and assertion replay controls.
