Skip to content

Interview PrepEnterprise SSO · Advanced

SAML Security and Operations ​

124. How are SAML assertions digitally signed? ​

The short answer

SAML uses XML Signature. The IdP takes the assertion, or the whole response, puts it into a standard byte form called canonicalisation, so whitespace and attribute order cannot change the result, computes a digest with SHA-256, and signs that digest with its private key, usually RSA-SHA256. The <ds:Signature> element is placed inside the signed element and records which element it covers, by its ID attribute in a Reference URI="#_a75adf55". The SP checks it with the IdP's public certificate from metadata.

What the signature block contains:

xml
<ds:Signature>
  <ds:SignedInfo>
    <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
    <ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/>
    <ds:Reference URI="#_a75adf55">
      <ds:Transforms>
        <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
        <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
      </ds:Transforms>
      <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
      <ds:DigestValue>…</ds:DigestValue>
    </ds:Reference>
  </ds:SignedInfo>
  <ds:SignatureValue>…</ds:SignatureValue>
</ds:Signature>

Reading it:

  1. Reference URI="#_a75adf55": the signature covers the element whose ID is _a75adf55, the assertion.
  2. enveloped-signature: remove this signature block before hashing, since it sits inside what it signs.
  3. xml-exc-c14n: canonicalise first, so harmless formatting changes do not break the hash.
  4. DigestValue: the SHA-256 of the canonical assertion.
  5. SignatureValue: the RSA signature over SignedInfo, which contains that digest.

Response or assertion? The IdP can sign the outer Response, the inner Assertion, or both. Signing the assertion is the most important, because the assertion is what the SP trusts. Many SPs require the assertion to be signed. Assertions can also be encrypted to the SP's certificate, so the browser cannot read attributes.

125. How is a SAML assertion validated and verified? ​

The short answer

The SP must: parse the XML safely, with external entities disabled; check the signature with the IdP's certificate and allowed algorithms, and confirm the signature covers the exact assertion it will read; check Issuer is the expected IdP; check Destination and Recipient equal its ACS URL; check Audience is its entity ID; check NotBefore and NotOnOrAfter with small clock tolerance; check InResponseTo matches a request it sent; reject a reused assertion ID; and only then read the NameID and attributes. Use a well-maintained library and keep it patched.

CheckStops
Safe XML parsing, no external entitiesXXE attacks that read files from the server
Signature valid with the IdP's certificateForged assertions
Signature covers the element you readSignature wrapping (question 127)
Issuer equals the configured IdPAssertions from another IdP
Destination, Recipient equal our ACS URLAssertions meant for another app
Audience is our entity IDSame
Time window, a minute or two of skewOld or future assertions
InResponseTo matches our requestUnsolicited, injected or replayed responses
Assertion ID not seen beforeReplay within the validity window

The order is not optional. Read user data only from the element the signature verified. Several real vulnerabilities came from libraries that verified one element and then read the NameID from another.

126. How do certificates work in SAML, and what happens when a certificate expires? ​

The short answer

The IdP signs with a private key, and publishes the matching public key inside an X.509 certificate in its metadata. The SP stores that certificate, or trusts the metadata URL, and uses it to check signatures. SAML certificates are usually self-signed: trust comes from exchanging metadata, not from a certificate authority. When the IdP's signing certificate expires or is replaced and the SP has not loaded the new one, every login for that customer fails with a signature error. So rotation must be planned with an overlap.

Rotating a SAML signing certificate without an outage:

  1. Add the new certificate to the IdP's metadata as a second signing key, while still signing with the old one.
  2. Update the SP to trust both. SPs that read the metadata URL do this automatically; others need the new certificate pasted in by an admin.
  3. Switch the IdP to sign with the new key.
  4. Confirm logins work for every SP.
  5. Remove the old certificate from both sides after it is no longer used.

Microsoft Entra ID, for example, lets you create a new certificate, keep it inactive while SPs are updated, then make it active, and it emails admins before a certificate expires.

Does expiry itself matter? Many SP libraries check only the key, not the certificate's dates, so an "expired" certificate may keep working. Do not rely on that. Some SPs do enforce dates, and an IdP will stop using an expired certificate anyway.

Encryption certificates are the reverse. If assertions are encrypted, the SP publishes its own certificate, the IdP encrypts with it, and the SP must rotate that one with the same overlap.

127. How does SAML prevent replay attacks and assertion tampering? ​

The short answer

Tampering is stopped by the XML signature: changing any signed byte breaks it. But the SP must also make sure the signature covers the element it actually reads, or an attacker can use signature wrapping: keep the original signed assertion somewhere in the document so the signature still checks, and add a forged unsigned assertion that the app reads instead. Replay is stopped by a short NotOnOrAfter window, Recipient and Audience checks, InResponseTo tying the response to one request, and the SP remembering assertion IDs until they expire.

genuine responseResponseAssertion ID=_a1, signedNameID: mallory@acmeSignature → #_a1 ✓after signature wrappingResponseAssertion ID=_evil, unsignedNameID: admin@acmehidden in Extensions:original _a1, signature ✓
A valid signature on the wrong thing. The attacker, who has a legitimate account, keeps the IdP's signed assertion for themselves intact but tucks it away. A vulnerable SP finds a valid signature somewhere in the document, then reads the first assertion it sees, the forged admin one.

This is a live problem, not history. In 2024 and 2025, signature-bypass bugs of this kind were found in widely used libraries, such as ruby-saml, which affected GitLab, and samlify, a common Node.js SAML library. Defences:

  1. Use a maintained library, and apply its security updates quickly.
  2. Require the assertion to be signed, and reject documents with more than one assertion.
  3. Read the identity only from the element whose ID the signature references.
  4. Validate the document against the SAML schema before processing.

Replay defences, together:

CheckLimits replay to
NotOnOrAfter of a few minutesThat window
Recipient and AudienceThis SP only
InResponseToThe one browser and request that started the login
Stored assertion IDs until expiryExactly one use

128. How would you troubleshoot a SAML login failure? ​

The short answer

First capture the actual SAML response, with the browser's network tab, a SAML tracer extension, or the SP's debug log, and decode it from Base64. Then compare it, field by field, with what the SP expects: the Issuer against the configured entity ID, the Destination and Audience against the SP's ACS URL and entity ID, the signing certificate against the one the SP has stored, the time window against both servers' clocks, the NameID format and the attribute names. Also check the IdP's sign-in logs, which often name the error directly.

The most common failures, and their fixes:

Error or symptomUsual causeFix
Invalid signatureIdP rotated its certificate; SP has the old oneUpdate the SP's certificate or metadata
Audience mismatchSP entity ID typed differently at the IdP, often a trailing slashMake them identical
Destination or Recipient mismatchACS URL differs: http vs https, a port, a pathFix the registered ACS URL
Assertion expired or not yet validClock drift on a serverSync time with NTP; small skew allowance
User not foundNameID format or attribute name differs from what the SP expectsMap the right attribute; agree on the format
User not assignedUser or group not assigned to the app at the IdPAssign them
Login loopSP session cookie not set on the ACS POST, often SameSiteSet the right cookie attributes (the ACS question)
Works for IdP-initiated, fails for SP-initiatedInResponseTo state lost, for example across load-balanced serversStore request state in a shared store

Decoding a captured response in Node:

ts
import { inflateRawSync } from 'node:zlib'

const xml = Buffer.from(samlResponseFromForm, 'base64').toString('utf8')       // POST binding
// for the Redirect binding, the message is also DEFLATE-compressed:
const req = inflateRawSync(Buffer.from(decodeURIComponent(samlRequestParam), 'base64')).toString('utf8')

129. How would you design SAML login for an enterprise application? ​

The short answer

Make SSO per tenant: each customer organisation gets its own IdP connection, with its entity ID, SSO URL and certificates, ideally imported from their metadata URL. Use SP-initiated login with home realm discovery by email domain. Validate assertions with a maintained library. Link users by a stable ID such as a persistent NameID or object ID, not email. Map groups to roles per tenant. Support JIT and SCIM provisioning. Offer an "enforce SSO" setting with a break-glass admin. Monitor certificate expiry. Give admins a self-service setup page with test logins and clear errors.

The data model:

TableHolds
tenantsCustomer organisation, verified email domains, "SSO required" flag
saml_connectionsTenant, IdP entity ID, SSO URL, certificates, metadata URL, attribute mapping
identitiesTenant, IdP entity ID, stable subject, linked local user
role_mappingsTenant, IdP group name, local role

The login path, step by step:

  1. The user types asha@acme.example. The app finds the tenant by its verified domain, acme.example.
  2. The app sends an AuthnRequest to that tenant's IdP and stores the request ID in a shared store.
  3. The response arrives at a single ACS URL, or one per tenant, such as /saml/acs/acme.
  4. The library validates the response against that tenant's certificate and entity ID only.
  5. The app finds the identity by tenant, issuer and subject, or creates a user just in time if the tenant allows it.
  6. Roles come from the tenant's group mappings.
  7. A new session starts.

Security points to mention:

  1. Verify domain ownership before a tenant can claim acme.example, with a DNS TXT record. Otherwise a rival could route Acme's users to their own IdP.
  2. Never accept an assertion from tenant A's IdP for a user of tenant B.
  3. Keep a break-glass login for the tenant's admin, protected by a passkey, for when their IdP is misconfigured.

130. How would you support customers using both SAML and OIDC? ​

The short answer

Put a single identity broker layer in front of your application. Each tenant's connection is either SAML or OIDC, but the broker turns both into the same internal result: tenant, issuer, stable subject, email, name and groups. Everything after that, account linking, role mapping, JIT provisioning and session creation, is shared code that does not know which protocol was used. You can build the broker with libraries, or use a product such as Keycloak, Auth0, Okta, WorkOS or Entra External ID, which speak both protocols outward and give your app one OIDC integration.

Acme: Entra IDSAMLGlobex: OktaOIDCInitech: GoogleOIDCidentity brokervalidate per protocolnormalise to:tenant · iss · subemail · groupsyour appone path: link,roles, session
Many protocols in, one shape out. Each customer keeps the protocol their IdP supports. The broker hides the difference, so the rest of your code handles exactly one kind of identity.

The normalised identity, in TypeScript:

ts
type ExternalIdentity = {
  tenantId: string
  protocol: 'saml' | 'oidc'
  issuer: string            // SAML entity ID or OIDC iss
  subject: string           // persistent NameID or OIDC sub
  email?: string            // only if the IdP vouches for it
  name?: string
  groups: string[]
}

Mapping between the two protocols:

ConceptSAMLOIDC
Who issued itIssuer, the entity IDiss
Stable user IDPersistent NameID or an object ID attributesub
Intended appAudienceaud
ExpiryNotOnOrAfterexp
Request bindingInResponseTostate and nonce
Profile dataAttribute statementClaims
LogoutSLOFront-channel and back-channel logout

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Interview Prep
Authentication & Identity
Cookies & sessions
Authentication
Tokens
OAuth & OIDC
Enterprise SSO
Directories
Authorization
Other topics
Nothing picked yet