Dev.to Security ๐Ÿ” Cybersecurity ๐Ÿ‘ 0 ๐Ÿ“– 7 min read

Validating SAML Responses: Signatures, Audience & Clock Skew

During a security review of a client's SSO integration, I found that their SAML endpoint accepted a response that was perfectly signed by the customer's identity provider, but issued for a completely different applicatio

Validating SAML Responses: Signatures, Audience & Clock Skew

During a security review of a client's SSO integration, I found that their SAML endpoint accepted a response that was perfectly signed by the customer's identity provider, but issued for a completely different application. The IdP was shared: the same Okta tenant also signed assertions for the customer's HR tool. The app checked the signature and the certificate, then trusted the NameID. It never compared the Audience with its own entity ID. Anyone at that customer with access to the HR tool's SSO flow could, in principle, have replayed an HR assertion into the SaaS app. Nothing exotic, no XML trickery, just one missing comparison. We fixed it in an afternoon, and it is the reason this post exists.

I wrote this with help from AI tools and checked the details against the SAML 2.0 Core and Profiles specifications, the OWASP SAML Security Cheat Sheet, and the documentation of the maintained libraries mentioned below. I am a Principal Software Engineer in Karachi with 9+ years across PHP/Laravel, Vue, Node and .NET microservices, and I build the free developer utilities at PixelValut Tools. Everything here is about validating SSO in your own application, against your own test tenants.

๐Ÿ“š Series Navigation โ€” Enterprise SSO & Identity for B2B SaaS

  • Part 1: Enterprise SSO Readiness: SAML vs OIDC for B2B SaaS
  • Part 2 (This Post): Validating SAML Responses: Signatures, Audience & Clock Skew
  • Part 3: SCIM Provisioning & Deprovisioning That Actually Removes Access
  • Part 4: Multi-Tenant Login Routing: Domain Discovery & Enforced SSO
  • Part 5: Just-in-Time Provisioning & Role Mapping From IdP Groups
  • Part 6: Break-Glass Accounts & SSO Audit Logs

Related earlier posts: Step-Up Authentication for Sensitive Actions ยท Session Lifecycle Hardening: Rotation, Timeouts & Server-Side Revocation

What must you validate in a SAML response?

Direct answer: Verify the signature with the certificate pinned for that specific connection, and make sure the signed element is the assertion you actually read. Then check Issuer, Audience, Recipient/Destination, NotBefore and NotOnOrAfter with one to three minutes of clock skew, InResponseTo against a stored request ID, and reject any assertion ID you have already seen.

Wall clock beside a server rack status panel, AI-generated

The order of checks

A SAML response arrives as a Base64-encoded XML document posted by the browser to your Assertion Consumer Service (ACS) URL. The browser is the courier, which means the user (or anyone controlling their browser) can see and modify it. Every check below exists because the response is untrusted input until proven otherwise.

I enforce them in this order, failing closed at the first problem:

  1. Find the connection first. Look up the identity connection from the request context (the RelayState or the stored AuthnRequest), not from the Issuer in the response. Never let the response choose which certificate validates it.
  2. Signature. Verify with the certificate stored for that connection. Require the assertion to be signed (or the response and the assertion). Reject unsigned assertions even if the outer response is signed, unless your library guarantees the signed response covers the assertion you read.
  3. Signed element = consumed element. The library must hand you the assertion it verified, not re-query the original document by tag name. This is the defence against XML signature wrapping attacks.
  4. Issuer. Must equal the IdP entity ID configured for this connection.
  5. Audience. Must contain your SP entity ID for this connection.
  6. Recipient and Destination. Must equal your ACS URL exactly, including scheme and path.
  7. Time window. NotBefore โ‰ค now + skew and NotOnOrAfter > now โˆ’ skew, on both Conditions and SubjectConfirmationData.
  8. InResponseTo. Must match an AuthnRequest ID you issued and have not consumed yet. If you support IdP-initiated SSO, treat it as a separate, explicitly enabled path.
  9. Replay. Store the assertion ID until its NotOnOrAfter and reject duplicates.

Checks at a glance

Check XML location What failure lets through Typical library setting
Signature ds:Signature on Assertion/Response Forged identity wantAssertionsSigned: true
Pinned certificate Connection settings, not the XML Attacker-supplied key idp.x509cert per connection
Issuer saml:Issuer Assertion from another IdP idp.entityId
Audience Conditions/AudienceRestriction Assertion meant for another app sp.entityId + strict mode
Recipient / Destination SubjectConfirmationData, Response@Destination Assertion meant for another ACS sp.assertionConsumerService.url
Time window Conditions, SubjectConfirmationData Old or future-dated assertion clock skew setting
InResponseTo SubjectConfirmationData@InResponseTo Unsolicited or swapped responses requestId validation
Replay cache Assertion@ID Same assertion used twice Your own cache

Laravel example with onelogin/php-saml

In PHP I use onelogin/php-saml (directly or through a Laravel wrapper) with strict mode on. Strict mode turns on the Audience, Destination, Recipient and time checks; the replay cache is still yours to add.

use OneLogin\Saml2\Auth;
use Illuminate\Support\Facades\Cache;

public function acs(Request $request, IdentityConnection $conn)
{
    $settings = [
        'strict' => true,
        'sp' => [
            'entityId' => route('saml.metadata', $conn),
            'assertionConsumerService' => ['url' => route('saml.acs', $conn)],
        ],
        'idp' => [
            'entityId' => $conn->settings['idp_entity_id'],
            'x509certMulti' => ['signing' => $conn->settings['certs']], // rotation
        ],
        'security' => [
            'wantAssertionsSigned' => true,
            'rejectUnsolicitedResponsesWithInResponseTo' => true,
        ],
    ];

    $auth = new Auth($settings);
    $requestId = $request->session()->pull("saml_req_{$conn->id}");
    $auth->processResponse($requestId);

    if ($auth->getErrors() || ! $auth->isAuthenticated()) {
        Log::warning('saml.reject', ['conn' => $conn->id, 'reason' => $auth->getLastErrorReason()]);
        abort(403);
    }

    $assertionId = $auth->getLastAssertionId();
    $ttl = max(60, $auth->getLastAssertionNotOnOrAfter() - time() + 180);
    if (! Cache::add("saml_seen_{$conn->id}_{$assertionId}", 1, $ttl)) {
        abort(403); // replay
    }

    return $this->loginLinkedIdentity($conn, $auth->getNameId());
}

Three details matter here. The connection comes from the route, so the response cannot pick its own trust anchor. x509certMulti lets you accept the old and new certificate during a rotation. And Cache::add is atomic, so two concurrent posts of the same assertion cannot both succeed.

Node example with @node-saml/node-saml

import { SAML } from '@node-saml/node-saml';

const saml = new SAML({
  callbackUrl: `https://app.example.com/sso/${conn.id}/acs`,
  issuer: `https://app.example.com/sso/${conn.id}`,      // your SP entity ID
  audience: `https://app.example.com/sso/${conn.id}`,
  idpIssuer: conn.settings.idpEntityId,
  idpCert: conn.settings.certs,                            // array for rotation
  wantAssertionsSigned: true,
  acceptedClockSkewMs: 120_000,
  validateInResponseTo: 'always',
  requestIdExpirationPeriodMs: 5 * 60_000,
  cacheProvider: redisCacheProvider,                       // shared across instances
});

const { profile } = await saml.validatePostResponseAsync(req.body);

validateInResponseTo: 'always' with a shared cache provider matters once you run more than one app instance; the default in-memory cache will reject valid logins that land on a different node.

Clock skew: how much is sane?

Clock problems cause most of the "SSO randomly fails for some users" tickets I see. IdPs typically issue assertions valid for about five minutes. If your server drifts, valid logins fail; if you allow huge skew, an intercepted assertion stays useful longer. I allow 120 seconds, run NTP (chrony) on every app host, and alert when drift passes 2 seconds.

chronyc tracking | grep -E 'System time|Last offset'

When debugging a rejected login from a test tenant, decode the SAMLResponse with a Base64 decoder and paste the NotBefore / NotOnOrAfter values into a Unix timestamp converter to compare them with your server time. Do this only with your own test logins, never with real users' assertions, and remember that decoding is for reading; validation stays in code.

Logging rejections without leaking assertions

Log the connection, the failed check and the assertion ID, never the full XML (it contains personal data and is a replayable credential until it expires). A structured reason makes customer IT calls much shorter: "Audience mismatch: expected https://app.example.com/sso/42, got https://app.example.com/sso/41" tells them exactly which field to fix.

Diagnostic checklist

  • [ ] Connection is resolved from route/RelayState, never from the response Issuer
  • [ ] Certificate is pinned per connection; rotation supported with two certs
  • [ ] Assertions must be signed; the verified element is the one you read
  • [ ] Issuer, Audience, Recipient and Destination compared exactly
  • [ ] NotBefore/NotOnOrAfter checked with 1โ€“3 minutes skew; NTP monitored
  • [ ] InResponseTo validated against a shared, expiring request store
  • [ ] Assertion IDs cached until expiry to block replay
  • [ ] IdP-initiated SSO disabled unless explicitly enabled per connection
  • [ ] Rejections logged with a reason, without the raw XML

FAQ

Is signature validation enough?

No. A valid signature only proves the IdP issued the assertion. Audience, Recipient and InResponseTo prove it was issued for your app, your endpoint and this login attempt.

Should I require the response or the assertion to be signed?

Require the assertion to be signed. Many IdPs sign both; that is fine. What matters is that the element your code reads is covered by a verified signature.

Should I allow IdP-initiated SSO?

Only when a customer needs it, enabled per connection. It cannot use InResponseTo, so the replay cache and short validity window carry more weight.

What clock skew should I allow?

One to three minutes is common. Fix server time with NTP rather than raising the skew when users report failures.

Can I parse the XML myself to read attributes?

Avoid it. Read attributes only from the object your library returns after validation, so you never read data from an unsigned part of the document.

How do I handle certificate rotation?

Store multiple certificates per connection, accept both during an agreed window, then remove the old one. Refreshing the IdP metadata URL on a schedule helps catch changes early.

Next in this series, Part 3 covers SCIM provisioning and deprovisioning that actually removes access when someone leaves.

Follow & Connect

๐Ÿ“ฐ Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes โ€” full credit and traffic to the original publisher.