JsonMind
API & Contracts12 min readUpdated Nov 17, 2026

Webhook Signature Verification: HMAC-SHA256, Timestamps, and Replays

Verify webhook signatures over the raw request body with HMAC-SHA256, timestamped schemes, constant-time comparison, replay windows, key rotation, and retry-safe 2xx handling.

JMBy JsonMind EngineeringLast reviewed: Nov 17, 2026Reviewed against primary specifications and linked sources.
Quick answer

Verify a webhook by computing an HMAC-SHA256 over the exact raw request body, not over a parsed and re-serialized object. Compare the digest in constant time, reject timestamps outside a short tolerance, deduplicate event IDs, and accept both old and new secrets during rotation. Return a 2xx only after the event is verified and durably queued for asynchronous processing.

Key takeaways
  • A signature authenticates the bytes the provider sent, so the raw body must reach the HMAC unchanged; parsing and re-serializing JSON silently breaks most first implementations.
  • Timestamped schemes such as Stripe-Signature bound replay to a tolerance window, but a valid timestamp still allows replay inside that window, so event-level idempotency is mandatory.
  • Compare signatures with a constant-time function over decoded bytes, store secrets per endpoint and environment, and fail closed when the secret is missing.
  • Rotation needs overlapping secrets: deploy acceptance of the new secret first, switch provider signing second, and remove the old secret only after the retry window drains.
  • Return 2xx after verification and durable enqueue, never after full processing; retries are normal, and a slow synchronous handler turns one delivery into duplicates.

A webhook endpoint is an unauthenticated route that performs privileged work: it marks invoices paid, ships orders, or provisions accounts. The only thing separating a genuine delivery from an attacker's POST is a signature computed over bytes that both sides possess. That sentence hides the failure behind most incidents: the provider signs the exact bytes it transmitted, while the receiver verifies a parsed, reordered object that no longer matches.

Verification is not a library call pasted into a handler. It is a byte-level contract plus operational decisions about clocks, retries, key rotation, and what a 2xx promises. The sections below build that contract for HMAC-SHA256 schemes, using Stripe and GitHub as references.

What a webhook signature proves, and what it does not

A valid signature proves two things: the body was not modified after signing, and whoever signed it knew the shared secret. It does not prove freshness, because only a timestamp inside the signed payload does that, and it does not prove the event is new, because a captured request can be replayed. It proves nothing after the secret leaks.

TLS covers a different gap: it protects each hop, but a TLS-terminating proxy or internal queue can still forward a forged body. Signatures travel with the message and survive retries and storage. Treat them as message authentication, then validate the event schema and business invariants separately: a correctly signed event can still claim a refund larger than the charge.

Sign the raw request body, never a re-serialized object

JSON is text, not a canonical format. The same object can be written with different whitespace, key order, escaping, and number formatting. JSON.parse followed by JSON.stringify normalizes those differences and destroys the signature. Duplicate keys, Unicode escapes, and large integers make it worse, and the provider's HMAC covers the bytes on the wire.

Every framework offers a way to keep them. In Express, mount express.raw({ type: "application/json", limit: "1mb" }) before the global JSON parser, or capture the buffer in the verify callback. In the Next.js App Router, call await req.text() before parsing; in FastAPI, await request.body(); in Django, request.body; in Flask, request.get_data(). Parse only after verification, never re-serialize to sign again.

Two details matter. Cap the body size before hashing so an attacker cannot force you to buffer gigabytes, and do not gate verification on Content-Type: GitHub can send form-encoded bodies, and the signature covers the exact bytes. A proxy that rewrites the body or normalizes line endings is a verification bug, not a provider bug.

HMAC-SHA256 and timestamped signature schemes

RFC 2104 defines HMAC as a keyed hash built from two nested hashes, with the key padded to the block size and mixed through inner and outer pads. HMAC-SHA256 is the standard choice: 32-byte output, no length-extension weakness, and broad support. Do not hand-roll it, and do not substitute SHA-256 of body plus secret; concatenation is not a MAC.

A timestamped scheme signs a string containing time and body, typically ${timestamp}.${rawBody}. Stripe's Stripe-Signature header uses this shape with a Unix timestamp in seconds. The timestamp limits how long a captured request stays useful, but only if the verifier enforces a tolerance; Stripe's libraries default to 300 seconds. Reject anything older or implausibly far in the future, and keep hosts on NTP so clock skew does not reject real deliveries.

The code below implements the contract for a Stripe-style header: parse every v1 value, rebuild the signed string from the raw buffer, and compare decoded bytes in constant time. The HMAC generator reproduces a digest from a known key and message.

import crypto from "node:crypto";

type ParsedHeader = { timestamp: number; signatures: string[] };

function parseSignatureHeader(header: string): ParsedHeader {
  const timestamp = Number(header.match(/(?:^|,)t=(\d+)/)?.[1]);
  const signatures = [...header.matchAll(/(?:^|,)v1=([0-9a-f]{64})/g)].map((m) => m[1]);
  if (!Number.isInteger(timestamp) || signatures.length === 0) {
    throw new Error("malformed signature header");
  }
  return { timestamp, signatures };
}

export function verifyWebhook(
  rawBody: Buffer,
  header: string,
  secrets: string[],
  toleranceSeconds = 300
): boolean {
  const { timestamp, signatures } = parseSignatureHeader(header);
  if (Math.abs(Math.floor(Date.now() / 1000) - timestamp) > toleranceSeconds) return false;
  const signed = Buffer.concat([Buffer.from(`${timestamp}.`, "utf8"), rawBody]);
  return secrets.some((secret) => {
    const expected = crypto.createHmac("sha256", secret).update(signed).digest();
    return signatures.some((hex) => {
      const candidate = Buffer.from(hex, "hex");
      return candidate.length === expected.length && crypto.timingSafeEqual(candidate, expected);
    });
  });
}

Multiple signatures are normal during rotation: validate all and accept the event if any matches, rather than stopping at the first.

Constant-time comparison and secret storage

String equality leaks information through timing: === can return as soon as two strings differ, so an attacker who measures many attempts can learn a valid prefix. The risk over a network is small, but the fix is one call. Node has crypto.timingSafeEqual, Python hmac.compare_digest, PHP hash_equals, Go hmac.Equal, Java MessageDigest.isEqual. Compare decoded bytes, not hex strings, and check the length first because some functions throw on mismatched lengths. Catch that error and return false; a 500 turns forgery attempts into log noise and retries.

Treat secrets like any signing key: generate at least 32 random bytes with a CSPRNG, store them in a secret manager, and keep separate secrets per endpoint and environment. Never commit one, reuse it as an encryption key, or log the full header. Redact signature headers in access logs and error trackers; a leaked secret lets anyone forge events until rotation completes.

Fail closed. A missing secret, empty allowlist, or unset environment variable must reject the request, not skip verification. The most common severe bug is a conditional that verifies only when a secret happens to be configured, silently turning production into an unauthenticated endpoint after a bad deploy.

Replay windows, event IDs, and idempotent handlers

A timestamp tolerance shrinks the replay window; it does not close it. An attacker can resend a captured request within those five minutes, and a retry can deliver the same event twice. Idempotency is part of verification, not an optimization. Record the event ID, such as Stripe's evt_... or GitHub's X-GitHub-Delivery UUID, under a unique constraint, and apply side effects in the transaction that records it. Keep records longer than the retry horizon.

GitHub illustrates the split: X-Hub-Signature-256 covers only the body, so replay defense depends on delivery IDs and idempotent handlers. Stripe's timestamp adds a bound, but retries still duplicate events. Exactly-once side effects come from a database constraint plus an outbox or an upsert keyed by event ID, not from the webhook layer. Delivery order is not guaranteed either: compare the event's own timestamp or version, or refetch the object from the provider API before a destructive change. Verify, deduplicate, then run business logic.

Key rotation with multiple active secrets

Rotation is a sequence, not a single edit. Generate the new secret, add it to the verifier while the old one still works, deploy, then switch provider signing to the new secret. Keep both active until old-signed deliveries have drained: at least the full retry window, since Stripe retries for up to three days and manual redeliveries can happen later. Only then remove the old secret.

Stripe supports this directly: during a roll it can include multiple v1 signatures in Stripe-Signature, so a verifier that checks every candidate keeps working. For your own scheme, put a key identifier such as kid in the header and look the secret up by ID instead of trying every secret blindly. Bound the list so a malformed header cannot force unbounded HMAC work.

Emergency rotation after a leak is different. Add the new secret, remove the compromised one immediately, and accept that deliveries signed with it fail. Replay missed events from the provider dashboard using recorded IDs, rather than keeping a known-compromised secret alive for convenience. Test the sequence in staging before you need it at 3 a.m.

Stripe-Signature and X-Hub-Signature-256 compared

Stripe sends Stripe-Signature: t=1492774577,v1=5257a8..., where t is a Unix timestamp in seconds and each v1 is lowercase hex HMAC-SHA256 of ${t}.${rawBody} using the endpoint secret. Several v1 values can appear during rotation. Stripe's libraries verify tolerance and return the constructed event; if you implement it yourself, parse every pair, reject conflicting t values, and compare all v1 candidates.

GitHub sends X-Hub-Signature-256: sha256=<hex>, an HMAC-SHA256 of the raw body with the webhook secret. There is no timestamp, so the header cannot distinguish a replay from a retry; X-GitHub-Delivery and idempotency do that job. The older X-Hub-Signature header uses SHA-1 and must never be the only check. GitHub can also send form-encoded payloads, where the signed bytes include payload=.

PropertyStripe-SignatureX-Hub-Signature-256
Header nameStripe-SignatureX-Hub-Signature-256
AlgorithmHMAC-SHA256, hex v1HMAC-SHA256, hex after sha256=
Signed content${t}.${rawBody}raw body only
Timestampt in seconds, 300s default tolerancenone
Replay defensetolerance plus event ID idempotencydelivery ID plus idempotency
Rotation signalmultiple v1 signaturessecret change per webhook
Body typesJSONJSON or form-encoded

Replay a captured delivery with the HTTP request workbench using the original headers and body; it quickly confirms whether middleware rewrites the payload before your verifier sees it.

Delivery retries, 2xx timing, and asynchronous processing

Providers treat any non-2xx as a failed delivery and retry. Stripe retries with exponential backoff for up to three days; GitHub does not automatically redeliver most webhooks and surfaces failed deliveries for manual replay. A 2xx promises you have taken responsibility, so send it only after verification and durable persistence or enqueueing. A 200 before the write lets a crash lose the event; a 200 after full processing lets a slow call exceed the provider timeout and duplicate.

The durable pattern is short: verify, insert the event ID and payload into a queue or table in one transaction, commit, then return 202 or 200. A worker consumes the row, performs side effects idempotently, and moves failures to a dead-letter queue with alerts. Keep p99 well under the provider timeout; draining the body and closing promptly also frees capacity.

Choose status codes deliberately. Return 400 for a malformed header or invalid JSON, 401 or 403 for a missing or invalid signature, 413 for an oversized body, and 5xx only for internal failures that deserve a retry. Never return 200 for an unverified event, and never echo the expected signature, the secret, or a stack trace.

Verification checklist and failure response policy

Test verification from outside the process, with a captured payload and a real signature, not a unit test that bypasses HTTP. These commands reproduce a Stripe-style signature with OpenSSL and send it with curl, proving that raw bytes, header format, and tolerance agree.

# Reproduce a Stripe-style signature: HMAC-SHA256 over "<timestamp>.<raw body>"
body='{"id":"evt_123","type":"invoice.paid"}'
ts=$(date +%s)
secret='whsec_test_secret'
sig=$(printf '%s.%s' "$ts" "$body" | openssl dgst -sha256 -hmac "$secret" -hex | sed 's/^.*= //')
curl -sS -o /dev/null -w '%{http_code}\n' https://api.example.com/webhooks/stripe \
  -H 'Content-Type: application/json' \
  -H "Stripe-Signature: t=$ts,v1=$sig" \
  --data-binary "$body"

Change one body character and confirm a 4xx; send it twice and confirm one side effect. Then work through the checklist.

CheckHow to testPass criteria
Raw bodySign pretty-printed JSON over its exact bytes2xx, parsed event matches
Missing signatureDelete the header4xx, no side effect, alert
Invalid signatureFlip one hex character4xx, no side effect
Expired timestampSign ten minutes in the past4xx at 300-second tolerance
Duplicate deliverySend the same event twice2xx both times, one side effect
Rotation overlapSign with old and new secretsboth accepted until old is removed
Secret hygieneSearch logs and error trackerno secret or full header
Fail closedUnset the secret in stagingrequests rejected, not accepted
ResponseWhen to use itProvider behavior
200 or 202Verified and durably queuedno retry
400Malformed header or invalid payloadretry likely; fix quickly
401Missing or invalid signatureretry likely; alert on spikes
413Body too largeretry likely
429Deliberate backpressureretry with backoff
500 or 503Internal failureretry; page on-call

After verification, the JSON formatter helps inspect the event while debugging, but keep it out of the signing path: formatting is exactly what breaks signatures. A check passes only with production configuration, not a verifier that skips secrets in development.

Common mistakes and production rules

These failures recur in audits:

  • Verifying after JSON.parse, or signing JSON.stringify(req.body).
  • Ignoring the timestamp and accepting any t, which keeps captured requests valid forever.
  • Accepting unsigned events when the secret is missing, usually through if (secret) verify().
  • Comparing hex strings with === instead of decoded bytes in constant time.
  • Logging the full signature header, the secret, or a payload that contains personal data.
  • Keeping a single secret and editing it in place, causing a failure window during rotation.
  • Returning 200 before persistence, then losing the event on a crash.
  • Trusting TLS alone, or verifying at the edge but not at the origin service.
  • Omitting a body size cap, or parsing before verification, exposing the parser to hostile input.
  • Using the webhook URL, a query token, or IP allowlisting as the authentication mechanism.

The rules fit in a paragraph. Verify raw bytes with a vetted HMAC implementation and constant-time comparison; enforce a short timestamp tolerance and an idempotency record keyed by event ID; keep secrets per endpoint and environment in a secret manager, with overlapping rotation; return 2xx only after a durable enqueue; alert on invalid-signature spikes; and keep captured payloads as test vectors in CI so a middleware change cannot silently break the contract.

Frequently asked questions

Why does my webhook signature fail after I parse the JSON?

Parsing and re-serializing changes whitespace, key order, escape sequences, and number formatting, so the bytes no longer match what the provider signed. Verify the raw body first, then parse a copy for business logic.

Is HMAC-SHA256 still the right choice for webhook signatures?

Yes. HMAC-SHA256 is standardized by RFC 2104, has no practical forgery or length-extension weakness when used with a random secret, and is what Stripe and GitHub use. The algorithm is rarely the weak point; raw-body handling, comparison, and key management usually are.

How do I stop replay attacks when the timestamp is inside the tolerance?

You cannot stop a replay with the timestamp alone. Record the provider event ID or delivery ID with a unique constraint before applying side effects, and keep that record longer than the provider retry window. The timestamp only shrinks the window; idempotency closes it.

How can I rotate a webhook secret without losing events?

Add the new secret while still accepting the old one, deploy that change, then switch the provider to sign with the new secret. Keep both active until every retry signed with the old secret has drained, and remove the old secret only after that window closes.

Should I return 200 before processing the event?

Return 2xx only after the signature is verified and the event is durably stored or enqueued. A 2xx before persistence tells the provider to stop retrying, so a crash loses the event; waiting for full processing risks a timeout and duplicate deliveries.

Reviewed against primary specifications and linked sources.

JsonMind guides are written and reviewed by the engineering team. We check each guide against the relevant RFC or vendor documentation, link the primary sources, and update the guide when behavior changes.

Primary sources are linked at the end of each guide.

References

Put this guide into practice

Browse all tools

Open the browser tool. Inputs stay in your browser and are not uploaded to the business server.

Related guides

All guides