Contact
EngineeringNov 20, 2026ยท20 min read

Add SAML SSO to SaaS: 12 Responses Tested on node-saml

KT
Keplaris TeamNov 20, 2026
A blue line carries a sealed envelope from an identity provider pillar to three tenant doors, where only the matching door glows green and a second envelope lies rejected beside the base

To add SAML SSO to a SaaS app, give each tenant its own SSO connection, validate every signed response with a maintained library, and take the tenant from that connection. The connection holds the ACS URL and SP entity ID you give the customer, plus their IdP's issuer and signing certificate. Then you decide how users get created (just in time or SCIM) and whether that tenant must use SSO.

The validation step is where the defaults bite. We sent 12 SAML responses to @node-saml/node-saml 5.2.0. With only the required options set, it accepted 3 attacks plus 1 unsolicited login we recommend rejecting, including a replayed response and one addressed to another tenant's login endpoint. With the six hardening options we list below set, 1 was still accepted: the response addressed to the other tenant. A 10-line check of our own closed it.

The top results we read in full for "add SAML SSO to SaaS" on 2026-11-20 come from companies that sell SSO, and none we read sends bad responses to a real service provider library. Keplaris, a New York product engineering studio, builds auth flows for SaaS products as part of our API and SaaS development work. We ran the 12 responses under 3 configurations three times on 2026-11-20 with identical results; the script and unedited output are at the end. We don't sell an SSO product.

How to add SAML SSO to a SaaS app: the short answer

Adding enterprise SAML SSO to a multi-tenant app is six jobs, and only one of them is SAML parsing. In order:

  1. Create an SSO connection per tenant: their IdP's entity ID, SSO URL and signing certificates, plus your SP entity ID and ACS URL for that tenant.
  2. Swap values with the customer: you give the ACS URL and SP entity ID; they give their issuer, SSO URL and certificate, usually as a metadata file.
  3. Route each login to the right connection, by verified email domain, subdomain or an org-specific login URL.
  4. Validate the response with a maintained library, hardening options set explicitly, plus the Destination and Recipient check below.
  5. Map the user to the tenant that owns the connection, keyed on the IdP's stable user identifier.
  6. Provision and enforce: create users just in time or through SCIM, and let each tenant require SSO.

One login traced through those steps, using the tenant from our test. Tenant acme has SP entity ID https://app.example.com/saml/acme, ACS URL https://app.example.com/saml/acme/acs and an IdP whose issuer is https://idp.acme.example/saml.

  1. Jane types jane@acme.example. The domain is verified for acme, so the app loads acme's connection and builds an AuthnRequest. node-saml records the request ID in its cache.
  2. Acme's IdP signs a Response for jane@acme.example with InResponseTo set to that request ID, and her browser posts it to acme's ACS URL.
  3. node-saml verifies the signatures against acme's certificate and checks the issuer, audience, time window and request ID, then consumes the ID so the response can't be used again.
  4. Our endpoint check confirms the Response's Destination and the assertion's Recipient are acme's ACS URL.
  5. The tenant_id comes from acme's connection row, and the request runs with that tenant set, as in our multi-tenant SaaS architecture guide.

What we tested, and what got through

Each response is a valid login with exactly one thing changed, built and signed by a test IdP inside saml-test.mjs: two RSA-2048 keys made with openssl (tenant acme and a second tenant, globex), signatures by xml-crypto 6.4.0 using RSA-SHA256. The service provider is @node-saml/node-saml 5.2.0 on Node v24.20.0, in three configurations:

  • Library defaults: callbackUrl, issuer, idpCert and audience set, plus entryPoint so the test can build a login request; nothing else.
  • Hardened: the six hardening options we list: idpIssuer, validateInResponseTo: "always", rejectReplayedAssertions, a 5 minute request-ID lifetime (requestIdExpirationPeriodMs), 30 s clock skew (acceptedClockSkewMs) and a 10 minute maximum assertion age (maxAssertionAgeMs).
  • Hardened + endpoint check: hardened, then our code checks that Destination and every bearer Recipient equal this tenant's ACS URL.

Results from run 1 (2026-11-20T07:52:47.699Z). The script cuts each error message at 60 characters, and this table shortens long messages further, marking the cut with "...". Wrong accepts are in bold.

ScenarioExpectedLibrary defaultsHardenedHardened + endpoint check
Valid SP-initiated loginAcceptAcceptedAcceptedAccepted
Same response posted twice (replay)Reject 2ndAccepted twice2nd rejected: InResponseTo is not valid2nd rejected: InResponseTo is not valid
Unsolicited response, no InResponseTo (IdP-initiated)PolicyAcceptedRejected: InResponseTo is missing from responseRejected: InResponseTo is missing from response
NameID changed after signingRejectRejected: Invalid document signatureRejected: Invalid document signatureRejected: Invalid document signature
Signed by another tenant's IdP keyRejectRejected: Invalid document signatureRejected: Invalid document signatureRejected: Invalid document signature
Audience is another SPRejectRejected: SAML assertion audience mismatch. Expected: https://app.exam...SameSame
Expired 10 minutes agoRejectRejected: No valid subject confirmation found among those available in...SameSame
Response signed, assertion unsignedRejectRejected: Invalid signatureRejected: Invalid signatureRejected: Invalid signature
Right key, wrong issuer nameRejectAcceptedRejected: Unknown SAML issuer. Expected: https://idp.acme.example/samlSame
NameID with an XML comment inside, signed by the IdPFull NameIDAccepted, full NameIDAccepted, full NameIDAccepted, full NameID
Addressed to another tenant's ACS (Destination and Recipient)RejectAcceptedAcceptedRejected: Destination https://app.example.com/saml/globex/acs is not t...
Signature wrapping (one variant only): forged assertion before the signed oneRejectRejected: Invalid document signature (stopped by the signed-Response default)SameSame

How to read it:

  • Defaults let 3 attacks plus 1 policy case through. The replay, the wrong issuer and the wrong ACS are attacks. The unsolicited response counts as wrong only because we recommend rejecting IdP-initiated logins.
  • Hardened let 1 through: the response addressed to globex's ACS, which node-saml 5.2.0 only logs.
  • Six attacks were rejected everywhere: NameID tampering, another tenant's key, wrong audience, expiry, an unsigned assertion and one signature-wrapping variant, which the signed-Response default stopped before node-saml's deeper checks ran.

The hardened replay was caught by the request-ID cache, not rejectReplayedAssertions, so this run doesn't show what that option does alone. The comment row returned jane@acme.example.evil.example in full; in 2018 several SAML libraries were found to cut a NameID at an XML comment (CERT VU#475445), and 5.2.0 does not. If your app uses one SP entity ID for every tenant, the audience check cannot tell tenants apart, and Destination and Recipient are all that tie a response to one tenant's endpoint.

SAML terms for the setup call: ACS URL, entity ID and metadata

The setup call with a customer's IT admin swaps a few values: your ACS URL and SP entity ID for their issuer, SSO URL and signing certificate, usually as one metadata file. Most confusion comes from two names for one thing, SP entity ID and Audience.

TermWhat it isWho owns itIn our example
IdP (identity provider)The customer's login system that signs responses, for example Okta, Microsoft Entra ID (formerly Azure AD) or Google WorkspaceCustomerhttps://idp.acme.example/saml
SP (service provider)Your app, which receives and validates responsesYouAcme's tenant in your app
AssertionThe signed statement inside a Response: who the user is, for whom, until whenIdP writes, you checkjane@acme.example
ACS URLThe endpoint the IdP posts the Response to; appears as Destination and RecipientYou give ithttps://app.example.com/saml/acme/acs
SP entity ID / AudienceYour app's name for this connection; the IdP writes it into the AudienceYou give ithttps://app.example.com/saml/acme
Issuer (IdP entity ID)The IdP's name, written in every Response and assertionYou ask for ithttps://idp.acme.example/saml
MetadataAn XML file carrying entity ID, endpoints and certificatesBoth sidesExchanged once, again on rotation
NameIDThe user identifier in the assertionIdPAn email address in our test
RelayStateAn opaque value the IdP passes back, often the page to return toYouValidate it against an allow-list before redirecting; never read the tenant from it

Key users on a stable identifier, a persistent NameID or the IdP's user ID attribute, not an email address: a reassigned email would sign the new owner into the old account.

SAML or OIDC: which to support first

Support SAML first if you sell to enterprises, and design the connection model so OIDC can slot in later. SAML 2.0 has been an OASIS standard since 15 March 2005, and enterprise IdPs such as Okta, Microsoft Entra ID and Google Workspace all support it. OIDC is simpler (JSON and JWTs instead of signed XML). Everything after validation is shared: connection row, routing, tenant mapping, provisioning and enforcement. With a protocol column, the second protocol is a new validator, not a new system.

SP-initiated vs IdP-initiated login

Reject IdP-initiated logins unless a customer contract requires them. In an SP-initiated login your app sends an AuthnRequest and the Response answers it with InResponseTo, which lets you accept each response once. In an IdP-initiated login the user clicks your tile in their portal and the Response arrives unsolicited. Rows 2 and 3 of our table show the difference: under the default validateInResponseTo: "never", node-saml accepted both; with "always", it rejected both.

If a contract requires IdP-initiated login, the README's combination is validateInResponseTo: "ifPresent" plus rejectReplayedAssertions: true, which remembers each assertion ID until it expires. It needs a shared cache with an atomic saveIfAbsentAsync. We did not test it.

Multi-tenant SSO: one connection per tenant

Multi-tenant SSO comes down to one rule: each tenant gets its own connection row, and the tenant is whatever that row says, nothing else. A sketch of the tables (not part of the test; adapt the types to your stack):

create table sso_connections (
  id               uuid primary key,
  tenant_id        uuid not null references tenants(id),
  protocol         text not null default 'saml',   -- 'saml' or 'oidc'
  sp_entity_id     text not null unique,           -- https://app.example.com/saml/acme
  acs_url          text not null unique,           -- https://app.example.com/saml/acme/acs
  idp_entity_id    text not null,                  -- https://idp.acme.example/saml
  idp_sso_url      text not null,
  idp_certs        text[] not null,                -- old and new during rotation
  enforced         boolean not null default false  -- users on the tenant's verified domains must use SSO
);

create table sso_domains (
  domain      text primary key,                    -- acme.example: one tenant per domain
  tenant_id   uuid not null references tenants(id),
  txt_token   text not null,                       -- random value the customer publishes in DNS
  verified_at timestamptz                          -- null until the TXT record is found
);

The domain's primary key means a domain routes to one tenant. idp_certs is an array because node-saml's idpCert accepts several, so during rotation you trust old and new at once; store each certificate's expiry and warn the tenant's admin before it, since once the IdP signs with a certificate you don't hold, every login fails. A per-tenant SP entity ID and ACS URL give two independent checks (audience and endpoint). If a tenant can run two connections, key those URLs on the connection, not the tenant slug.

Routing a login to the right tenant (home realm discovery)

Picking the connection before validation is usually called home realm discovery. Three common ways: the email domain the user types, matched against a verified row in sso_domains; a tenant subdomain such as acme.app.example.com; or an org-specific login URL. The email-domain route is the friendliest and the one that depends on domain verification.

Domain verification with a DNS TXT record

Verify every domain before it routes logins. Otherwise a tenant could claim globex.example, receive globex users' login attempts and, with automatic account linking, take over their accounts. You generate a random token per domain, the customer publishes it as a DNS TXT record, and your app looks it up before setting verified_at.

Linking existing password accounts

Link an existing password account to an SSO identity only when its email is on a domain verified for that same tenant and the account already belongs to that tenant; anything else gets a new account or a manual step. After the first link, store the IdP's stable identifier and match on that.

Take the tenant from the connection, not the hostname

The session's tenant comes from the connection that verified the response, never from the hostname, the email domain in the assertion or a form field. It is the rule from our multi-tenant architecture guide: accept a tenant only after checking it against the verified identity.

What to check in every SAML response, and the node-saml settings for it

A service provider must check seven things in every response before it creates a session. Each item names what enforces it in node-saml 5.2.0:

  1. The signature covers the element you read: wantAuthnResponseSigned and wantAssertionsSigned, both true by default.
  2. The Issuer is this tenant's IdP: idpIssuer, unset by default.
  3. The Audience is your SP entity ID: audience, which defaults to issuer.
  4. Destination and every bearer Recipient are this tenant's ACS URL: not enforced in 5.2.0; our checkEndpoints below.
  5. InResponseTo matches a request you sent: validateInResponseTo: "always" and a short requestIdExpirationPeriodMs.
  6. The time window is valid: acceptedClockSkewMs and maxAssertionAgeMs.
  7. The response is used once: the request-ID cache, plus rejectReplayedAssertions.

The 5.2.0 defaults favour compatibility. Each line below states the default it overrides; connection and sharedCache are placeholders (the tested run used the PEM file and the in-memory cache).

import { SAML } from "@node-saml/node-saml"; // 5.2.0

const saml = new SAML({
  callbackUrl: "https://app.example.com/saml/acme/acs",  // this tenant's ACS
  issuer: "https://app.example.com/saml/acme",           // our SP entity ID
  audience: "https://app.example.com/saml/acme",         // default is issuer; never false
  idpCert: connection.certs,                             // string[]: old + new during rollover
  entryPoint: connection.ssoUrl,
  idpIssuer: "https://idp.acme.example/saml",            // default unset: wrong issuer was accepted
  validateInResponseTo: "always",                        // default "never": replay + unsolicited accepted
  rejectReplayedAssertions: true,                        // default false (new in 5.2.0)
  requestIdExpirationPeriodMs: 5 * 60_000,               // default 8 h
  acceptedClockSkewMs: 30_000,                           // default 0
  maxAssertionAgeMs: 10 * 60_000,                        // default 0 (no limit)
  cacheProvider: sharedCache,                            // default in-memory: one process only
  // README says to set these explicitly (default sha1); not exercised by our matrix:
  signatureAlgorithm: "sha256",
  digestAlgorithm: "sha256",
});

Notes on the choices, all from the node-saml 5.2.0 README:

  • Time limits. The OASIS security considerations (section 6.4.1) say clocks should differ by at most a few minutes and assertions should live a few minutes. Five minutes is also enough for a login request.
  • signatureAlgorithm and digestAlgorithm control what node-saml signs, not what it accepts; our test IdP signed with RSA-SHA256, the minimum the OWASP SAML Security Cheat Sheet recommends.
  • Leave wantAssertionsSigned and wantAuthnResponseSigned at true. Four of our rejections (table rows 4, 5, 8 and 12) came from the signature checks they turn on; the signature wrapping section shows the source line.

The check node-saml 5.2.0 does not make: Destination and Recipient

node-saml 5.2.0 accepts a response whose Destination or Recipient is another endpoint, so your app has to check both. The SAML security considerations (section 6.4.2) say the SP MUST check the Recipient. The 5.2.0 README says that "the next major version checks received responses against callbackUrl" and that "until then a response that fails either check is accepted". In the library source, the functions warnIfDestinationIsNot and warnIfNoBearerConfirmationNames in lib/saml.js only call the debug logger, visible with NODE_DEBUG=node-saml.

This is checkEndpoints from our script, verbatim:

// node-saml 5.2.0 only logs a Destination or Recipient mismatch (its next major version rejects it),
// so the app checks both itself, after validation passed, on a response with exactly one assertion.
const NS = "urn:oasis:names:tc:SAML:2.0:assertion";
function checkEndpoints(b64, acs) {
  const doc = new DOMParser().parseFromString(Buffer.from(b64, "base64").toString(), "text/xml");
  const assertions = doc.getElementsByTagNameNS(NS, "Assertion");
  if (assertions.length !== 1) throw new Error(`expected 1 assertion, got ${assertions.length}`);
  const dest = doc.documentElement.getAttribute("Destination");
  const recips = [...assertions[0].getElementsByTagNameNS(NS, "SubjectConfirmationData")].map(e => e.getAttribute("Recipient"));
  if (dest !== acs) throw new Error(`Destination ${dest} is not this tenant's ACS`);
  if (!recips.length || recips.some(r => r !== acs)) throw new Error(`Recipient is not this tenant's ACS`);
}

Call it after node-saml has validated the response and before you create a session:

const { profile } = await saml.validatePostResponseAsync({ SAMLResponse: body.SAMLResponse });
checkEndpoints(body.SAMLResponse, connection.acsUrl); // after validation, before creating a session

Three design choices in those ten lines:

  • Exactly one assertion. OWASP warns against looking up security elements by tag name, since the lookup can find an element the signature never covered. Ours is safe only because it runs after node-saml verified the signatures and throws unless there is exactly one Assertion (node-saml already refuses more than one, so this is a second lock).
  • Recipient as well as Destination. A comment in the node-saml source reads "An unsigned Response's Destination is not verified". The Recipient sits inside the signed assertion, so checking it covers responses with an unsigned envelope.
  • Exact string match. The next major version compares parsed URLs, per the README; ours is stricter, so store the ACS URL exactly as you give it to the customer.

Our wrong-ACS row changed both values, so the check stopped at Destination. Remove the check only after upgrading to a version that enforces both and re-running a test like ours.

Signature wrapping and the SAML library CVEs to patch

Signature wrapping means the library verifies one XML node and the app reads another: if verification finds the signed assertion by its ID and the code that reads the user takes the first assertion it finds, a forged one placed first picks the user. In the USENIX Security 2012 paper "On Breaking SAML", Somorovsky and colleagues found critical wrapping flaws in 11 of 14 major SAML frameworks. To prevent it, read the user only from the element the signature verified, require a signed Response or signed assertion, reject any response with more than one assertion, and keep the SAML library and its XML signature dependency patched (the CVEs below are this class).

The shape of the attack we ran in row 12:

<samlp:Response>                      (not signed)
  <saml:Assertion ID="forged">        read by vulnerable code: NameID admin@acme.example
  </saml:Assertion>
  <saml:Assertion ID="_a...">         verified: the IdP's signature covers this one
    <ds:Signature> Reference URI="#_a..." </ds:Signature>
    NameID jane@acme.example
  </saml:Assertion>
</samlp:Response>

node-saml 5.2.0 rejected it with "Invalid document signature" at lines 897-898 of lib/saml.js: with the default wantAuthnResponseSigned: true, a Response without a valid signature is refused before the library counts assertions. This is one variant only, stopped by the signed-Response default; it does not test the multiple-assertion check behind it. The tampered-NameID and other-tenant-key responses failed at that same check, because their Response signature did not verify.

The root cause recurs. node-saml's own CVE-2025-54369 advisory reads: "Node-SAML loads the assertion from the (unsigned) original response document. This is different than the parts that are verified when checking signature." In ruby-saml, GitHub Security Lab showed (2025-03-12) that two XML parsers in the same library could select different Signature elements, with an exploitable instance in GitLab. Recent advisories from the GitHub Advisory Database, read 2026-11-20:

CVELibraryWhat went wrongFixed in
CVE-2025-54369@node-saml/node-saml, legacy node-samlAssertion read from the unsigned original document5.1.0; legacy node-saml 3.1.2 and earlier have no fix
CVE-2025-54419@node-saml/node-saml, @node-saml/passport-saml, passport-samlAssertion read from the unsigned document instead of the verified part5.1.0 for both @node-saml packages; passport-saml 3.2.4 and earlier have no fix
CVE-2025-29774, CVE-2025-29775xml-cryptoMultiple SignedInfo references; a comment in DigestValue6.0.1, 3.2.1, 2.1.6
CVE-2024-45409ruby-samlIncorrect XPath selector1.12.3, 1.17.0
CVE-2025-25291, CVE-2025-25292ruby-samlParser differential between REXML and Nokogiri1.12.4, 1.18.0
CVE-2025-66567, CVE-2025-66568ruby-samlIncomplete fix for CVE-2025-25292; canonicalization returning an empty string1.18.0
CVE-2025-47949samlifySignature wrapping2.10.0

Pin the SAML library and its XML signature dependency to exact versions, subscribe to their advisories, and re-run a test like ours after every upgrade.

Running more than one server: share the cache

Run the default cache on two or more instances and validateInResponseTo: "always" rejects legitimate logins. The README says the in-memory provider "is not sufficient across multiple servers or processes: the instance that generated the request ID may not be the one that handles the response". Back it with Redis or your database by implementing this interface (signatures from the README and lib/types.d.ts in 5.2.0, comments ours):

interface CacheProvider {
  saveAsync(key: string, value: string): Promise<CacheItem | null>;
  getAsync(key: string): Promise<string | null>;
  removeAsync(key: string | null): Promise<string | null>;
  // Optional: remove and return atomically, so only one of two concurrent copies is accepted.
  consumeAsync?(key: string): Promise<string | null>;
  // Needed by rejectReplayedAssertions: save until expiresAtMs if absent, atomically.
  saveIfAbsentAsync?(key: string, value: string, expiresAtMs: number): Promise<boolean>;
}

consumeAsync and saveIfAbsentAsync must be atomic: in Postgres, delete ... returning and insert ... on conflict do nothing; in Redis, GETDEL and SET with NX and PX. We have not tested a shared cache, so test both methods under concurrency before you trust them.

JIT provisioning vs SCIM: creating and removing users

SAML signs a user in; it does not tell you when they leave. Just-in-time (JIT) provisioning creates the account on first login from the assertion's attributes, which is enough to launch. It never deprovisions: when the customer disables an employee, your app hears nothing, and that person keeps access until their session ends.

SCIM closes that gap: the customer's IdP calls your API to create, update and deactivate users and groups, and its provisioning hook is where IdP groups map to roles inside the tenant. Building SCIM is a separate project. Until you have it, keep SSO sessions short so a disabled account loses access within hours, not weeks.

Enforcing SSO without locking customers out

Let each tenant require SSO, and keep a way in for when their IdP breaks. The pieces:

  • A require-SSO flag per connection (enforced above). When it's on, users on verified domains can't use a password or magic link; the login form sends them to their IdP.
  • A break-glass admin. At least one account per tenant that can sign in another way, with MFA, so a bad certificate doesn't lock the customer out. Log every use.
  • An audit trail. Log when a connection is created or changed, a certificate is replaced, enforcement is toggled, and an SSO login fails.
  • Session lifetime. Your session, not the IdP's, decides how long a user stays signed in; set it per tenant if customers ask.
  • Single logout: start with your own session. We didn't test SAML single logout (SLO); treat IdP-wide logout as a separate feature.
  • Gate setup on the plan. If SSO is a paid feature, check the sso entitlement on the server before a tenant can create a connection, as in our SaaS entitlements guide.
  • Rate-limit the ACS endpoint by IP before authentication, like any pre-auth route (SaaS API rate limiting).

Build on a library or buy a broker

Build on a library when you expect a handful of connections and someone on the team will own SAML; buy when you expect many connections across many IdPs and nobody will. The routes, in no ranked order:

RouteExamplesWhat you payWhat you still own
SP library@node-saml/node-saml 5.2.0, samlify 2.15.1, ruby-saml 1.18.1, python3-saml 1.16.0Engineering timeEverything in this post: options, endpoint check, cache, patching
Open-source brokerOry Polis (formerly BoxyHQ SAML Jackson, now part of Ory), KeycloakHosting and upkeepRunning and patching it, tenant mapping
Hosted brokerWorkOS, Clerk, Stytch, Auth0Per connection (below)Tenant mapping, provisioning policy, enforcement

Hosted per-connection prices, as listed on 2026-11-20:

  • WorkOS: $125 per SSO connection per month for 1 to 15 connections, $100 for 16 to 30, $80 for 31 to 50, $65 for 51 to 100.
  • Clerk: Pro and Business include 1 SSO connection per app; extra connections cost $75 a month each for 2 to 15 and $60 for 16 to 100.
  • Stytch: B2B includes 5 SSO or SCIM connections, then $125 per connection.
  • Auth0: B2B Essentials includes 3 enterprise SSO connections and B2B Professional 5, then $100 a month per additional connection, up to 30 in total (the Free plan lists 1).

A broker earns its fee when connection count grows faster than anyone's interest in SAML. Even with a broker, the tenant mapping, domain verification and enforcement stay in your app. For the general cost model, see build vs buy software.

What this test does not prove

This is one library and a test IdP in code, not a pen test or a security audit.

  • One library, one IdP. We tested @node-saml/node-saml 5.2.0 against responses we signed ourselves, not Okta, Entra ID or Google Workspace, which format responses differently.
  • Not tested: other signature-wrapping classes, encrypted assertions, single logout, metadata fetching, certificate rotation, rejectReplayedAssertions on its own, IdP-initiated login with "ifPresent", a Recipient-only mismatch, and any shared cache provider.
  • Our endpoint check reads elements by tag name, so it is only safe after node-saml has verified the response. Don't move it before validation.

Out of scope, and separate topics: roles and permissions inside a tenant, API keys for integrations (SSO is for people in browsers), and a SCIM build.

Full code and output

The full test script and the unedited output of run 1. Runs 2 and 3 on 2026-11-20 were identical apart from the timestamp on the first line.

To run it, make a folder with "type": "module" in its package.json, then generate your own test keys with the openssl command from the script header, once per tenant:

openssl req -x509 -newkey rsa:2048 -nodes -keyout idp-a.key -out idp-a.crt -days 30 -subj "/CN=test-idp-tenant-a"
openssl req -x509 -newkey rsa:2048 -nodes -keyout idp-b.key -out idp-b.crt -days 30 -subj "/CN=test-idp-tenant-b"
npm install @node-saml/node-saml xml-crypto @xmldom/xmldom
node saml-test.mjs

We used @node-saml/node-saml 5.2.0, xml-crypto 6.4.0 and @xmldom/xmldom 0.9.12 on Node v24.20.0. The keys are throwaway test keys; we don't publish ours, and you should never reuse these for anything else.

saml-test.mjs

// saml-test.mjs: what does a SAML service provider accept? A test IdP (two tenants' signing keys,
// made with openssl) issues responses; @node-saml/node-saml validates them, once with the library's
// defaults plus the required options, once hardened. Every response is built and signed here with
// xml-crypto, so each attack is exactly one change to a valid response.
//   openssl req -x509 -newkey rsa:2048 -nodes -keyout idp-a.key -out idp-a.crt -days 30 -subj "/CN=test-idp-tenant-a"
//   (same for idp-b), npm install @node-saml/node-saml xml-crypto @xmldom/xmldom, node saml-test.mjs
import { readFileSync } from "node:fs";
import { SAML } from "@node-saml/node-saml";
import { SignedXml } from "xml-crypto";
import { DOMParser } from "@xmldom/xmldom";

const key = t => readFileSync(`idp-${t}.key`, "utf8");
const crt = t => readFileSync(`idp-${t}.crt`, "utf8");
const SP = "https://app.example.com/saml/acme";             // tenant acme's SP entity ID
const ACS = "https://app.example.com/saml/acme/acs";
const IDP = "https://idp.acme.example/saml";

const iso = ms => new Date(Date.now() + ms).toISOString();
let n = 0;
const id = p => `_${p}${++n}${Math.random().toString(16).slice(2, 10)}`;

function assertionXml({ acs = ACS, nameId = "jane@acme.example", audience = SP, issuer = IDP, inResponseTo, notOnOrAfterMs = 5 * 60_000, aid = id("a") }) {
  const irt = inResponseTo ? ` InResponseTo="${inResponseTo}"` : "";
  return `<saml:Assertion xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ID="${aid}" Version="2.0" IssueInstant="${iso(0)}">` +
    `<saml:Issuer>${issuer}</saml:Issuer>` +
    `<saml:Subject><saml:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress">${nameId}</saml:NameID>` +
    `<saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer"><saml:SubjectConfirmationData${irt} NotOnOrAfter="${iso(notOnOrAfterMs)}" Recipient="${acs}"/></saml:SubjectConfirmation></saml:Subject>` +
    `<saml:Conditions NotBefore="${iso(-60_000)}" NotOnOrAfter="${iso(notOnOrAfterMs)}"><saml:AudienceRestriction><saml:Audience>${audience}</saml:Audience></saml:AudienceRestriction></saml:Conditions>` +
    `<saml:AuthnStatement AuthnInstant="${iso(0)}" SessionIndex="${id("s")}"><saml:AuthnContext><saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport</saml:AuthnContextClassRef></saml:AuthnContext></saml:AuthnStatement>` +
    `</saml:Assertion>`;
}

function sign(xml, tenant, idAttrValue) {
  const s = new SignedXml({
    privateKey: key(tenant), publicCert: crt(tenant),
    canonicalizationAlgorithm: "http://www.w3.org/2001/10/xml-exc-c14n#",
    signatureAlgorithm: "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256",
  });
  s.addReference({
    xpath: `//*[@ID='${idAttrValue}']`,
    transforms: ["http://www.w3.org/2000/09/xmldsig#enveloped-signature", "http://www.w3.org/2001/10/xml-exc-c14n#"],
    digestAlgorithm: "http://www.w3.org/2001/04/xmlenc#sha256",
  });
  s.computeSignature(xml, { location: { reference: `//*[@ID='${idAttrValue}']/*[local-name(.)='Issuer']`, action: "after" } });
  return s.getSignedXml();
}

// Build a response: assertion signed, then response signed (both, as most IdPs can be set to do).
function response(o = {}) {
  const { tenant = "a", signAssertion = true, signResponse = true, inResponseTo, mutate } = o;
  const aid = id("a");
  let a = assertionXml({ ...o, inResponseTo, aid });
  if (signAssertion) a = sign(a, tenant, aid);
  if (o.mutateAssertion) a = o.mutateAssertion(a);
  const rid = id("r");
  const irt = inResponseTo ? ` InResponseTo="${inResponseTo}"` : "";
  let r = `<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ID="${rid}" Version="2.0" IssueInstant="${iso(0)}" Destination="${o.acs ?? ACS}"${irt}>` +
    `<saml:Issuer>${o.issuer ?? IDP}</saml:Issuer><samlp:Status><samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/></samlp:Status>${a}</samlp:Response>`;
  if (signResponse) r = sign(r, tenant, rid);
  if (mutate) r = mutate(r);
  return Buffer.from(r).toString("base64");
}

// Required options only (cert, issuer, callback, audience). Everything else is the library default.
const base = { callbackUrl: ACS, issuer: SP, idpCert: crt("a"), audience: SP, entryPoint: "https://idp.acme.example/sso" };
const hardened = { ...base, idpIssuer: IDP, validateInResponseTo: "always", rejectReplayedAssertions: true,
                   requestIdExpirationPeriodMs: 5 * 60_000, acceptedClockSkewMs: 30_000, maxAssertionAgeMs: 10 * 60_000 };
const configs = {
  "library defaults": () => new SAML({ ...base }),
  "hardened": () => new SAML(hardened),
  "hardened + endpoint check": () => Object.assign(new SAML(hardened), { endpointCheck: true }),
};

// node-saml 5.2.0 only logs a Destination or Recipient mismatch (its next major version rejects it),
// so the app checks both itself, after validation passed, on a response with exactly one assertion.
const NS = "urn:oasis:names:tc:SAML:2.0:assertion";
function checkEndpoints(b64, acs) {
  const doc = new DOMParser().parseFromString(Buffer.from(b64, "base64").toString(), "text/xml");
  const assertions = doc.getElementsByTagNameNS(NS, "Assertion");
  if (assertions.length !== 1) throw new Error(`expected 1 assertion, got ${assertions.length}`);
  const dest = doc.documentElement.getAttribute("Destination");
  const recips = [...assertions[0].getElementsByTagNameNS(NS, "SubjectConfirmationData")].map(e => e.getAttribute("Recipient"));
  if (dest !== acs) throw new Error(`Destination ${dest} is not this tenant's ACS`);
  if (!recips.length || recips.some(r => r !== acs)) throw new Error(`Recipient is not this tenant's ACS`);
}

// Ask the SP for a login request so it records the request ID, then read the ID back.
async function issueRequest(saml) {
  const url = await saml.getAuthorizeUrlAsync("", undefined, {});
  const { inflateRawSync } = await import("node:zlib");
  const xml = inflateRawSync(Buffer.from(new URL(url).searchParams.get("SAMLRequest"), "base64")).toString();
  return xml.match(/ID="([^"]+)"/)[1];
}

const scenarios = [
  ["valid SP-initiated login", "accept", async s => [response({ inResponseTo: await issueRequest(s) })]],
  ["the same response posted twice (replay)", "reject 2nd", async s => { const r = response({ inResponseTo: await issueRequest(s) }); return [r, r]; }],
  ["unsolicited response, no InResponseTo (IdP-initiated)", "policy", async () => [response({})]],
  ["NameID changed after signing", "reject", async s => [response({ inResponseTo: await issueRequest(s),
      mutate: x => x.replace("jane@acme.example", "admin@acme.example") })]],
  ["signed by another tenant's IdP key", "reject", async s => [response({ tenant: "b", inResponseTo: await issueRequest(s) })]],
  ["audience is another SP", "reject", async s => [response({ audience: "https://app.example.com/saml/globex", inResponseTo: await issueRequest(s) })]],
  ["expired 10 minutes ago", "reject", async s => [response({ notOnOrAfterMs: -10 * 60_000, inResponseTo: await issueRequest(s) })]],
  ["response signed, assertion unsigned", "reject", async s => [response({ signAssertion: false, inResponseTo: await issueRequest(s) })]],
  ["right key, wrong issuer name", "reject", async s => [response({ issuer: "https://idp.evil.example/saml", inResponseTo: await issueRequest(s) })]],
  ["NameID with an XML comment inside (signed by the IdP)", "full NameID, not cut at the comment", async s => [response({ nameId: "jane@acme.example<!---->.evil.example", inResponseTo: await issueRequest(s) })]],
  ["addressed to another tenant's ACS (Recipient and Destination)", "reject", async s => [response({ inResponseTo: await issueRequest(s),
      acs: "https://app.example.com/saml/globex/acs" })]],
  ["signature wrapping: forged assertion inserted before the signed one", "reject", async s => {
    const irt = await issueRequest(s);
    return [response({ inResponseTo: irt, signResponse: false,
      mutate: x => x.replace("<saml:Assertion", assertionXml({ nameId: "admin@acme.example", inResponseTo: irt }) + "<saml:Assertion") })];
  }],
];

const ver = JSON.parse(readFileSync("node_modules/@node-saml/node-saml/package.json", "utf8")).version;
const xcv = JSON.parse(readFileSync("node_modules/xml-crypto/package.json", "utf8")).version;
console.log(`@node-saml/node-saml ${ver}, xml-crypto ${xcv}, Node ${process.version}, run ${new Date().toISOString()}`);
console.log(`"library defaults" = callbackUrl, issuer, idpCert, audience set; nothing else.`);
console.log(`"hardened" = also idpIssuer, validateInResponseTo "always", rejectReplayedAssertions, 30 s clock skew, 10 min max assertion age.`);
console.log(`"hardened + endpoint check" = hardened, then the app checks Destination and every bearer Recipient equal this tenant's ACS.\n`);
console.log("scenario | expected | library defaults | hardened | hardened + endpoint check");
for (const [name, expected, make] of scenarios) {
  const cells = [];
  for (const mk of Object.values(configs)) {
    const saml = mk();
    const out = [];
    for (const r of await make(saml)) {
      try {
        const { profile } = await saml.validatePostResponseAsync({ SAMLResponse: r });
        if (saml.endpointCheck) checkEndpoints(r, ACS);
        out.push(`accepted (${profile.nameID})`);
      } catch (e) { out.push(`rejected: ${String(e.message).split("\n")[0].slice(0, 60)}`); }
    }
    cells.push(out.join("; then "));
  }
  console.log(`${name} | ${expected} | ${cells.join(" | ")}`);
}

Output, run 1

@node-saml/node-saml 5.2.0, xml-crypto 6.4.0, Node v24.20.0, run 2026-11-20T07:52:47.699Z
"library defaults" = callbackUrl, issuer, idpCert, audience set; nothing else.
"hardened" = also idpIssuer, validateInResponseTo "always", rejectReplayedAssertions, 30 s clock skew, 10 min max assertion age.
"hardened + endpoint check" = hardened, then the app checks Destination and every bearer Recipient equal this tenant's ACS.

scenario | expected | library defaults | hardened | hardened + endpoint check
valid SP-initiated login | accept | accepted (jane@acme.example) | accepted (jane@acme.example) | accepted (jane@acme.example)
the same response posted twice (replay) | reject 2nd | accepted (jane@acme.example); then accepted (jane@acme.example) | accepted (jane@acme.example); then rejected: InResponseTo is not valid | accepted (jane@acme.example); then rejected: InResponseTo is not valid
unsolicited response, no InResponseTo (IdP-initiated) | policy | accepted (jane@acme.example) | rejected: InResponseTo is missing from response | rejected: InResponseTo is missing from response
NameID changed after signing | reject | rejected: Invalid document signature | rejected: Invalid document signature | rejected: Invalid document signature
signed by another tenant's IdP key | reject | rejected: Invalid document signature | rejected: Invalid document signature | rejected: Invalid document signature
audience is another SP | reject | rejected: SAML assertion audience mismatch. Expected: https://app.exam | rejected: SAML assertion audience mismatch. Expected: https://app.exam | rejected: SAML assertion audience mismatch. Expected: https://app.exam
expired 10 minutes ago | reject | rejected: No valid subject confirmation found among those available in | rejected: No valid subject confirmation found among those available in | rejected: No valid subject confirmation found among those available in
response signed, assertion unsigned | reject | rejected: Invalid signature | rejected: Invalid signature | rejected: Invalid signature
right key, wrong issuer name | reject | accepted (jane@acme.example) | rejected: Unknown SAML issuer. Expected: https://idp.acme.example/saml | rejected: Unknown SAML issuer. Expected: https://idp.acme.example/saml
NameID with an XML comment inside (signed by the IdP) | full NameID, not cut at the comment | accepted (jane@acme.example.evil.example) | accepted (jane@acme.example.evil.example) | accepted (jane@acme.example.evil.example)
addressed to another tenant's ACS (Recipient and Destination) | reject | accepted (jane@acme.example) | accepted (jane@acme.example) | rejected: Destination https://app.example.com/saml/globex/acs is not t
signature wrapping: forged assertion inserted before the signed one | reject | rejected: Invalid document signature | rejected: Invalid document signature | rejected: Invalid document signature

Frequently asked questions

How do I add SAML SSO to my SaaS app?

Create one SSO connection per tenant. Give the customer that tenant's ACS URL (for example https://app.example.com/saml/acme/acs) and SP entity ID (https://app.example.com/saml/acme), and ask for their IdP's issuer, SSO URL and signing certificate, usually as one metadata file. Route each login to the right connection, validate the signed response with a maintained library, and take the tenant from the connection, never from the email or hostname. In our test of 12 responses against @node-saml/node-saml 5.2.0, the defaults accepted 3 attacks plus 1 unsolicited login we recommend rejecting, and the six hardening options we list still let 1 through (a response addressed to another tenant's ACS), so set those options explicitly and check Destination and Recipient yourself.

Should a B2B SaaS support SAML or OIDC first?

SAML first if you are selling to enterprises. SAML 2.0 has been an OASIS standard since March 2005, and enterprise IdPs such as Okta, Microsoft Entra ID and Google Workspace all support it. Build the connection model so a tenant's connection can be either type, and add OIDC when a customer's IdP prefers it. The tenant mapping, provisioning and enforcement parts are the same for both.

Is IdP-initiated SSO safe to allow?

It is weaker than SP-initiated login because the response answers no request, so the InResponseTo check that stops replays cannot run. In our test, node-saml 5.2.0 with its defaults accepted an unsolicited response; with validateInResponseTo set to always it rejected it with 'InResponseTo is missing from response'. Reject IdP-initiated logins unless a customer contract requires them. If one does, use validateInResponseTo: 'ifPresent' with rejectReplayedAssertions: true and a shared cache; we did not test that combination.

What must a service provider check in every SAML response?

That the signature is valid and covers the element you actually read, that the Issuer is the tenant's IdP, that the Audience is your SP entity ID, that Destination and every bearer Recipient are this tenant's ACS URL, that InResponseTo matches a request you sent, that the time window is valid with a small clock skew, and that the assertion has not been used before. In our test, node-saml 5.2.0 with hardened settings rejected bad signatures, a wrong issuer, a wrong audience, an expired assertion and a reused request ID. It only logs a Destination or Recipient mismatch, so write that check yourself; its README says the next major version will enforce it.

What is SAML signature wrapping and how do I prevent it?

Signature wrapping is an attack where the library verifies one signed XML element and the app reads a different, forged one. Prevent it by reading the user only from the element the signature covered, requiring a signed Response or signed assertion, rejecting any response with more than one assertion, and patching your SAML library and its XML signature dependency on every advisory. In our test node-saml 5.2.0 rejected the one wrapping variant we sent, because its default requires a signed Response; we did not test other variants.

Does SAML SSO remove users when they leave the company?

No. SAML only authenticates a user at login. Just-in-time provisioning can create the account on first login, but nothing tells your app when the IdP disables that person, so they keep access until their session ends and simply cannot sign in again. Removing users when they leave needs SCIM, where the customer's IdP calls your API to create, update and deactivate accounts.

Should I build SAML SSO on a library or buy a broker?

A maintained library is enough when you expect a handful of connections and someone on the team owns SAML: sets the hardening options, adds the Destination and Recipient check, runs a shared cache and patches on advisories. Buy a hosted or open-source broker when you expect many connections across many IdPs and nobody will own that upkeep. As listed on 2026-11-20, WorkOS charges $125 per connection per month for its first 15 SSO connections and Stytch includes 5 before charging $125 each.

Next articleSaaS Entitlements: Feature Gating, Plan Limits and Stripe, Tested

Get in touch.

Whether you have questions or just want to explore what's possible, we're here to help.