If your application accepts webhooks from Stripe, GitHub, Shopify or Slack, every incoming POST request is an anonymous message from the internet until you prove otherwise. Webhook security mostly depends on one control: verifying payload signatures before your code acts on the data. This article explains how signature verification works, how to implement it without the subtle bugs that quietly disable it, and where the standard advice is not enough.
Why Webhook Endpoints Attract Attackers
A webhook endpoint is a public URL that runs business logic. It marks orders as paid, provisions accounts, triggers deployments and updates subscription tiers. Attackers find these endpoints in JavaScript bundles, leaked config files, public repositories and predictable paths like /webhooks/stripe or /api/hooks/payment.
Here is a pattern that shows up again and again in e-commerce audits. A team integrates a payment provider during a two-week sprint. The handler reads the event type, sees payment_intent.succeeded and changes the order status. During local testing, someone commented out the signature check because curl requests kept failing. That change shipped to production.
From then on, anyone who POSTs a crafted JSON body gets free goods. Nobody notices until finance reconciliation, often 3-4 weeks later, turns up dozens of “paid” orders with no matching payouts.
How Webhook Signature Verification Works
Most providers use HMAC-SHA256 with a shared secret. The provider computes an HMAC over the raw request body, often with a timestamp added, and sends the result in a header. Your server runs the same calculation with the same secret and compares the two values.
The details differ by provider, and the differences matter. GitHub sends X-Hub-Signature-256 as a hex digest with a sha256= prefix. Shopify sends X-Shopify-Hmac-Sha256 as base64. Stripe’s Stripe-Signature header contains a t= timestamp and a v1= signature, and the signed string is the timestamp, a dot, then the body. Slack signs v0:timestamp:body and sends the timestamp in its own header.
Some platforms use asymmetric signatures instead. Discord signs interaction requests with Ed25519, so the receiver verifies them with a public key and holds no secret that could leak. The Standard Webhooks specification (webhook-id, webhook-timestamp and webhook-signature headers) is also gaining adoption, which gives libraries one common format to support.
Implementing Webhook Payload Verification Step by Step
An experienced application security engineer reviews the order of operations first, then the cryptography. Verification has to happen before parsing, before database writes and before any logging that could trigger side effects.
1. Capture the raw request bytes before any framework middleware parses them.
2. Compute the HMAC with the secret loaded from a secrets manager such as AWS Secrets Manager or HashiCorp Vault, not from source code.
3. Compare signatures in constant time: crypto.timingSafeEqual in Node.js, hmac.compare_digest in Python, hash_equals in PHP.
4. Reject timestamps outside a tolerance window (Stripe’s libraries default to 300 seconds) and store processed event IDs so that replays are rejected.
5. Only then parse the JSON, return a 2xx response quickly and push the real work onto a queue.
There is a Node.js-specific catch in step 3: timingSafeEqual throws an error when the two buffers differ in length. Check the length first, and treat a length mismatch as a failed verification, not as an unhandled exception.
For teams of fewer than 10 people, the best advice is not to write this yourself. Official helpers such as stripe.webhooks.constructEvent, @octokit/webhooks and the Svix libraries already handle encoding, tolerance windows and multiple signatures during secret rotation.
Common Mistakes That Silently Break Verification
The most common bug is verifying re-serialized JSON. A developer applies express.json() globally and then computes the HMAC over JSON.stringify(req.body). Key order, whitespace and Unicode escaping change, so verification fails. Under deadline pressure, someone then “fixes” it by removing the check. In Express, use express.raw({ type: ‘application/json’ }) on the webhook route. In Django, use request.body. In Laravel, use $request->getContent().
The second mistake is failing open. Code such as “if the signature header is present, verify it” lets an attacker skip verification by leaving the header out. A try/catch that logs the error and keeps processing has the same effect. Missing or malformed signatures must stop the request.
The third mistake shows up behind load balancers. Twilio signs the full request URL together with the POST parameters. When TLS terminates at an AWS ALB or Cloudflare, the application sees http:// or an internal hostname, so every signature fails. The fix is to rebuild the public URL from X-Forwarded-Proto and the configured host. Disabling validation is not the fix.
Watch what you return on failure too. A response like “expected signature abc123, got def456” helps an attacker debug their forgery. Send a generic 400 or 401 response and keep the details in internal logs, as explained in error messages that leak too much detail.
Myth: HTTPS and IP Allowlists Make Signatures Unnecessary
TLS protects data in transit. It does not tell you who sent the request, because anyone can open a TLS connection to your endpoint. HTTPS is necessary, but it does not authenticate the sender.
IP allowlisting helps, but it is a weak primary control. GitHub publishes its hook ranges through the meta API and Stripe publishes its webhook IPs, but these lists change and cached copies go stale. Worse, if any internal service can be tricked into calling your webhook URL, the request comes from a trusted address. That is a classic SSRF attack path. “Secret” URL tokens are no better, because they end up in proxy logs, APM traces and error reports.
Some providers do not sign webhooks at all. In that case, treat the webhook as a notification only. Take the object ID from the payload and fetch the authoritative record from the provider’s API over an authenticated connection. Air-gapped or strictly on-prem environments often cannot accept inbound webhooks, and scheduled API polling is the safer design there.
Testing That Verification Actually Works
A security audit of a webhook handler should include five negative tests: no signature header, a wrong signature, a valid signature with one byte of the body changed, a timestamp outside the tolerance window, and a replayed event ID. All five must be rejected. Put these tests in CI so a future refactor cannot quietly remove the check.
Rotate secrets on a schedule and whenever a developer with access leaves. Use the provider’s overlap window so both secrets are valid for a short period, and never share one secret between staging and production. Webhook handlers should get the same scrutiny as any other endpoint covered by REST API security best practices, including rate limiting and request size limits.
FAQ: Webhook Signature Verification
Should a failed signature check return 400 or 401?
Either is acceptable, as long as the response body says nothing useful. Avoid 5xx responses, because most providers retry on 5xx and repeated retries add noise to your logs and alerts.
Is HMAC-SHA1 still safe for webhooks?
SHA-1 collision attacks such as SHAttered in 2017 do not directly allow HMAC forgery, so HMAC-SHA1 is not broken in practice. Still, prefer SHA-256 where the provider offers it. GitHub’s legacy X-Hub-Signature header uses SHA-1, and GitHub recommends the SHA-256 header instead.
Can automated vulnerability scanning detect weak webhook handling?
In part. External website security scanning finds exposed endpoints, verbose errors, missing security headers and weak SSL/TLS configurations. Confirming that signatures are enforced takes a targeted test: send an unsigned request in staging and check that it is rejected.
Key Takeaways for Webhook Security
Treat every webhook as untrusted input until its signature is verified against the raw bytes, compared in constant time and checked against a timestamp window. Fail closed, store event IDs to block replays, and use official SDK helpers instead of custom code. One practical tip: search your codebase today for webhook routes that use a JSON body parser. That single check often finds the handler where verification was quietly switched off.
