How to Verify Webhook Signatures Correctly
Webhooks transmit asynchronous event notifications between cloud platforms and your application servers. Because webhook HTTP endpoints must be publicly accessible on the internet, verifying cryptographic signatures is your primary defense against fraudulent events, unauthorized tampering, and replay attacks.
- Capture the Unmodified Raw Body: You must access the exact raw string or byte stream of the HTTP request before any framework middleware (such as
express.json(), Django request parser, or Spring Boot@RequestBody) deserializes it into an object or dictionary. - Extract Signature & Metadata Headers: Retrieve provider-specific signature headers (e.g.,
Stripe-Signature,X-Hub-Signature-256) and any companion headers like timestamps or delivery identifiers. - Construct the Canonical Signed Payload: Format the exact message template defined by the vendor. For example, Stripe and Svix mandate concatenating the integer timestamp with a period separator and the raw body (
{timestamp}.{raw_body}), whereas GitHub signs the raw payload alone. - Calculate HMAC with Webhook Secret: Execute an HMAC-SHA256 (or HMAC-SHA1) digest using your dedicated webhook signing secret and format the digest into hex or Base64 as specified.
- Compare in Constant Time: Always verify using a constant-time comparison helper like Node.js
crypto.timingSafeEqual(), Pythonhmac.compare_digest(), or PHPhash_equals()to thwart microsecond side-channel timing attacks.
Before & After Example: Fixing Express.js Raw Body Parsing
The single most frequent reason developers encounter invalid signatures is framework body parsers re-serializing JSON with altered whitespace or differing key order. Here is how to fix this in Express:
Before: Fragile JSON Middleware (Fails Signature Verification)
// ❌ BROKEN: express.json() converts body to an object; re-stringifying alters bytes!
const express = require('express');
const app = express();
app.use(express.json());
app.post('/webhook', (req, res) => {
// JSON.stringify(req.body) does NOT match the original byte-for-byte stream!
const computed = crypto.createHmac('sha256', SECRET)
.update(JSON.stringify(req.body))
.digest('hex');
// Result: Verification almost always FAILS!
});
After: Preserving Raw Body with verify callback
// ✅ SECURE & ACCURATE: Preserve raw buffer directly from the incoming stream
const express = require('express');
const crypto = require('crypto');
const app = express();
app.use(express.json({
verify: (req, res, buf) => {
// Preserve the pristine buffer directly from the network socket
req.rawBody = buf;
}
}));
app.post('/webhook', (req, res) => {
const signature = req.headers['x-hub-signature-256'];
const expected = 'sha256=' + crypto.createHmac('sha256', SECRET)
.update(req.rawBody)
.digest('hex');
if (crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected))) {
res.status(200).send('Verified');
} else {
res.status(400).send('Invalid signature');
}
});
Common Failure Causes & Diagnosing Inconsistencies
- Re-serialized JSON: Deserializing a webhook into a language object and converting it back with
JSON.stringifyorjson.dumpsalmost always changes byte ordering, key arrangement, and Unicode escapes. - Newline Conversions (CRLF vs LF): Git checkout settings, proxies, or Windows web servers often convert Unix line feeds (
\n) into carriage returns (\r\n). Even a single byte mutation yields a totally different cryptographic digest. - Test vs Production Key Confusion: Providers like Stripe issue different webhook signing secrets for CLI local test listening (
whsec_...) versus live production dashboard endpoints. - Timestamp Drift & Replay Tolerance: If your server's clock drifts by more than 300 seconds, or if you are replaying old captured test payloads, timestamp tolerance checks will reject the delivery even if the cryptographic hash matches.
Frequently Asked Questions
Why does my webhook signature not match?
Why must I use the raw body?
What is a timestamp tolerance?
Is my secret sent anywhere?
How does constant-time comparison prevent timing attacks?
Security & Privacy Notice
All signature calculations in this tool are executed locally using standard Web Cryptography (crypto.subtle). Secrets, headers, and request bodies never touch any server. As a general operational best practice, never enter production root secrets on third-party computers, and consider rotating any secrets that have been shared or exposed during debugging sessions.