How to Verify Webhook Signatures
Verify inbound webhook signatures with HMAC over the raw body, constant-time comparison, timestamp tolerance, and secret rotation, without breaking idempotency.
On this page
- Introduction
- How the signature scheme works
- Read the raw body, not the parsed JSON
- Verify with constant-time comparison
- Enforce timestamp tolerance against replay
- Rotate secrets and support multiple signatures
- Respond correctly and process idempotently
- Testing signature verification
- Common pitfalls
- Conclusion
Introduction
A webhook endpoint is a public URL that accepts state-changing requests from a third party. Without verification, anyone who learns the URL can POST a forged event and trigger whatever your handler does: a fake payment success, a fraudulent order, a spoofed deployment notice. Providers solve this by signing each delivery with a shared secret and sending the signature in a header. Your job is to recompute that signature over the exact bytes you received and reject anything that does not match.
This tutorial implements webhook signature verification. It covers the HMAC scheme, why the raw body matters, constant-time comparison, timestamp tolerances that defeat replay, secret rotation, correct responses, idempotent processing, and the tests that prove a forged request is rejected. The examples use Node.js with TypeScript, but the scheme is generic and applies to Stripe, GitHub, Shopify, and any provider that signs deliveries.
How the signature scheme works
The common scheme is an HMAC: signature = HMAC-SHA256(secret, signed_payload), where signed_payload is the timestamp joined with the raw request body, for example "1700000000." + bodyString. The provider sends the timestamp and the signature in headers (t= and v1= in Stripe’s format). You recompute the HMAC with your copy of the secret and compare. Because only you and the provider know the secret, a matching HMAC proves the payload came from the provider and was not modified.
The HMAC construction — hash a key together with the message — is what makes it resistant to length-extension attacks, unlike a plain HASH(secret + message). The signed string includes the timestamp so a captured request cannot be replayed later with a valid signature: the timestamp is inside the HMAC, so changing it invalidates the signature.
import { createHmac, timingSafeEqual } from 'node:crypto';
const TOLERANCE_SECONDS = 300; // 5 minutes
function signPayload(secret: string, timestamp: number, rawBody: string): string {
return createHmac('sha256', secret)
.update(`${timestamp}.${rawBody}`)
.digest('hex');
}
Read the raw body, not the parsed JSON
The most common verification bug is signing the parsed object instead of the raw bytes. Body-parser middleware consumes the stream and hands you an object; when you JSON.stringify that object it may reorder keys, drop insignificant whitespace, format a float differently, or change Unicode escapes. The HMAC then differs from the provider’s even though nothing was tampered with. Capture the raw buffer before any JSON middleware, keep it available on the request, and only parse it after verification succeeds.
// Express: capture raw bytes for the webhook route, then parse for the handler.
app.post(
'/webhooks/provider',
express.raw({ type: 'application/json' }), // raw Buffer, no JSON parsing yet
(req, res) => {
const rawBody = req.body.toString('utf8');
const ok = verifySignature(req.headers, rawBody, process.env.WEBHOOK_SECRET!);
if (!ok) return res.status(400).json({ error: 'invalid_signature' });
const event = JSON.parse(rawBody); // safe to parse after verification
return handleEvent(event, res);
},
);
If your framework parses bodies globally, carve out the webhook route with a raw-body parser scoped to that path. Verify against bytes, not strings decoded with the wrong charset: decode as UTF-8 only after you know the provider sends UTF-8, otherwise sign the raw buffer.
Verify with constant-time comparison
Compare the expected and received signatures with a timing-safe function, not ===. A byte-by-byte equality check can leak how many leading bytes match through response timing, which in principle lets an attacker guess the signature one byte at a time. Node provides crypto.timingSafeEqual, but it throws when the buffers differ in length, so check the length first and then compare.
Some providers send multiple signatures during rotation, or sign with several secrets, so accept if any candidate matches. Split the header on commas, strip the version prefix, and test each value.
function verifySignature(
headers: Record<string, string | string[] | undefined>,
rawBody: string,
secret: string,
): boolean {
const header = String(headers['provider-signature'] ?? '');
const parts = Object.fromEntries(
header.split(',').map((kv) => kv.split('=').map((s) => s.trim()) as [string, string]),
);
const timestamp = Number(parts['t']);
const provided = (header.match(/v1=([0-9a-f]+)/g) ?? []).map((s) => s.slice(3));
if (!Number.isFinite(timestamp) || provided.length === 0) return false;
// Reject stale or far-future timestamps before comparing signatures.
const age = Math.abs(Date.now() / 1000 - timestamp);
if (age > TOLERANCE_SECONDS) return false;
const expected = signPayload(secret, timestamp, rawBody);
const expectedBuf = Buffer.from(expected, 'hex');
return provided.some((sig) => {
const got = Buffer.from(sig, 'hex');
return got.length === expectedBuf.length && timingSafeEqual(got, expectedBuf);
});
}
Enforce timestamp tolerance against replay
The signature alone does not stop replay: a valid signature stays valid forever, so an attacker who captures one delivery can resend it. The timestamp tolerance is the defense. Reject deliveries whose timestamp is older than the tolerance, and compare Math.abs so a clock skew in either direction is bounded. Set the server clock with NTP so your Date.now() is close enough to the provider’s that legitimate deliveries are not rejected for skew.
Tolerance solves short-window replay, but not a replay within the window. For handlers that must be exactly-once, dedupe on the provider’s event id: store processed ids with a TTL and return a success without reprocessing when you see a duplicate. Verification says “this came from the provider and is fresh”; idempotency says “this has not already been processed.” You need both.
Rotate secrets and support multiple signatures
Secrets leak — through logs, a compromised config, or an ex-employee. Rotation must not drop deliveries, so the standard approach is an overlap window: the provider signs with the new secret and also with a secondary secret, and your endpoint accepts either until every sender is on the new one. Store secrets in an ordered list, verify against each, and remove the retired secret after the provider confirms the migration. Never hard-code the secret; load it from the environment or a secret manager, and never log it. If a secret is exposed, rotate immediately and treat every event signed with the old secret as suspect.
Respond correctly and process idempotently
Respond fast with a 2xx once you have verified and durably queued the event, and do the heavy processing asynchronously. Providers retry on non-2xx and on timeouts, so a slow synchronous handler causes duplicate deliveries. Return 400 for a bad signature without revealing which check failed, and 200 for both a fresh event and a duplicate you have already seen. Make the handler idempotent on the event id so retries and replays are harmless.
Testing signature verification
Test the adversarial paths. Assert that a body modified after signing is rejected, that a signature computed with the wrong secret is rejected, that a timestamp outside the tolerance is rejected, and that a correctly signed request is accepted. Assert that a signature valid for one body is not valid for a different body with the same timestamp.
import { signPayload } from './webhook';
test('rejects a tampered body and a stale timestamp', () => {
const secret = 'test_secret';
const now = Math.floor(Date.now() / 1000);
const body = JSON.stringify({ id: 'evt_1', amount: 100 });
const good = signPayload(secret, now, body);
expect(verify(secret, now, body, good)).toBe(true);
expect(verify(secret, now, body.replace('100', '999'), good)).toBe(false); // tampered
expect(verify(secret, now - 3600, body, good)).toBe(false); // stale
expect(verify('rotated_secret', now, body, good)).toBe(false); // wrong secret
});
Also test at the HTTP layer: post a raw body with a valid signature and assert the event is queued exactly once; post the same delivery twice and assert the second is acknowledged without a second side effect.
Common pitfalls
- Verifying the parsed JSON. Re-serialization changes the bytes and breaks the HMAC.
- Using
===. Non-constant-time comparison leaks signature bytes through timing. - Ignoring the timestamp. A valid signature without a freshness check is replayable.
- No tolerance bound. Unbounded age accepts arbitrarily old deliveries.
- One secret only. Rotation either drops deliveries or leaves the old secret live.
- Slow 2xx. Synchronous slow handlers invite provider retries and duplicates.
- No idempotency. A retried delivery processes twice and double-charges or double-ships.
- Logging the secret or raw payload. Secrets and PII leak into logs.
Conclusion
Webhook verification is HMAC over the raw body plus a timestamp, checked with a constant-time comparison and a bounded tolerance, with rotation support and idempotent handling behind it. Keep the raw bytes, compute HMAC-SHA256(secret, timestamp + body), accept any signature in the rotation list, reject stale timestamps, and respond fast while processing asynchronously. Test the tampered, stale, and wrong-secret cases, because those are the ones a forged request will try. Get this right and a public webhook URL becomes a trustworthy channel instead of an open door.
Sources: Stripe: Verify webhook signatures, GitHub: Validating webhook deliveries, RFC 2104: HMAC: Keyed-Hashing for Message Authentication.
FAQ
- Why can't I verify the signature on the parsed JSON body?
- Signing happens over the exact bytes the provider sent. Parsing JSON and re-serializing it changes key order, whitespace, number formatting, and Unicode escaping, so the bytes you hash no longer match. Always verify against the raw request body before any JSON middleware runs.
- What timestamp tolerance should I allow?
- Enough to cover clock skew and retries but short enough to bound replay. Five minutes is a common default; reduce it to one or two minutes when the provider retries quickly, and always compare the timestamp as an integer, not as a string.
- Do webhook signatures also need TLS?
- Yes. A signature proves the payload is authentic and unmodified, but it does not hide the payload or prevent an on-path observer from reading it. TLS protects confidentiality and integrity in transit; the signature protects integrity and authenticity end to end, and both are required.
Report a problem with this articleOpens a pre-filled issue on GitHub.