Introduction
A B2B SaaS lets each customer connect their payment gateway and receive payment webhooks on a shared endpoint. A security review finds three problems: signatures are compared with a normal string comparison, there is no check on the timestamp, and the tenant is identified by a field inside the unverified JSON body. Any of these could let an attacker mark invoices as paid.
Webhook security is mostly about a few precise details. Get them right once, in a shared library, and every integration benefits.
In this article you will learn how HMAC webhook signatures work, how to identify the tenant and its secret safely, how to compare signatures, how to reject replays, and how to rotate secrets without downtime.
How HMAC Signatures Work
The sender and receiver share a secret. For each request, the sender computes an HMAC, usually HMAC-SHA256, over a string that includes a timestamp and the exact raw request body, and sends the result in a header. The receiver recomputes the HMAC with its copy of the secret and compares. If anything in the body or timestamp changed, the values would differ.
Include the timestamp in the signed content so an attacker cannot reuse an old signature with a new timestamp. Many providers use a format like t=1767225600, v1=hexsignature in a single header.
Identifying the Tenant Before Trusting the Body
In a multi-tenant receiver, you need the tenant's secret before you can verify, but you must not trust anything in the body until it is verified. Resolve the tenant from something outside the body: a tenant-specific URL such as /webhooks/payments/ten_8f2a, or a header that carries an endpoint ID. Look up the secret for that endpoint, verify, and only then parse the payload.
Verifying Correctly in Code
Use the raw bytes of the body. Many frameworks parse JSON automatically, and re-serializing parsed JSON can change whitespace or key order, which breaks verification. Compare signatures in constant time so an attacker cannot learn the correct value byte by byte from response timing.
import crypto from "node:crypto";${ts}.
export function verifyWebhook(rawBody: Buffer, header: string, secrets: string[], toleranceSec = 300) {
const parts = Object.fromEntries(header.split(",").map(p => p.split("=")));
const ts = Number(parts.t);
if (!ts || Math.abs(Date.now() / 1000 - ts) > toleranceSec) return false;
const given = Buffer.from(parts.v1 ?? "", "hex");
return secrets.some(secret => {
const expected = crypto.createHmac("sha256", secret)
.update().update(rawBody).digest();
return given.length === expected.length && crypto.timingSafeEqual(given, expected);
});
}
The function accepts a list of secrets so a tenant can have an old and a new secret active during rotation.
Replay Protection
A valid signed request captured by an attacker remains valid forever unless you limit it. The timestamp tolerance, typically five minutes, limits the window. Inside that window, record each event ID or signature you have processed, with an expiry slightly longer than the tolerance, and reject any request whose ID you have already seen.
Store these IDs in Redis with a TTL or in a database table with a unique constraint and a cleanup job. Because many providers retry legitimate deliveries with the same event ID, respond to a duplicate with 200 rather than an error, and simply skip processing.
Secret Rotation and Asymmetric Options
Let tenants rotate secrets themselves. Generate a new secret, keep both old and new active for a set period, and remove the old one automatically. Store secrets encrypted and never log them or the computed signatures.
If you are the sender and want receivers to avoid holding shared secrets, consider asymmetric signatures such as Ed25519: you sign with a private key and publish the public key. Receivers can verify but cannot forge.
Practical Examples: Real-World Use Cases
The SaaS from the introduction moved to tenant-specific webhook URLs, constant-time verification over the raw body, a five-minute tolerance, and a Redis-based replay cache. The fixes took two days and closed all three findings.
A logistics platform sending webhooks to customers added a secret rotation screen with a 72-hour overlap. Customers rotate after staff changes without coordinating with support.
A procurement SaaS receiving events from several ERPs wrapped verification in shared middleware. New integrations now inherit correct signature, tolerance, and replay handling by default.
Common Mistakes to Avoid
Verifying a re-serialized body instead of the raw bytes.
Using == or === to compare signatures.
Identifying the tenant from inside the unverified payload.
Signing the body without a timestamp or not checking the timestamp.
Returning detailed error messages that reveal which check failed.
Best Practices: Actionable Tips
Put verification in one shared, well-tested module.
Support two active secrets per endpoint for rotation.
Keep timestamp tolerance short and servers synchronized with NTP.
Record processed event IDs for at least the tolerance window.
Write tests for tampered bodies, old timestamps, wrong tenants and replays.
Conclusion
Webhook security in multi-tenant receivers depends on a handful of exact steps: identify the tenant from the URL or a header, verify an HMAC over the timestamp and raw body in constant time, enforce a short timestamp window, reject replayed event IDs and support secret rotation. The takeaway: never act on a webhook until you have proved who sent it, when, and that you have not seen it before.
Secure Your Integrations With Parallaxis
Parallaxis builds multi-tenant SaaS platforms and integrations with secure webhook handling, secret management, and audit logs built in. If a security review has flagged your webhook endpoints, visit parallaxis.in to explore our SaaS development services or talk with our team.