General

Webhook Signature Verification Failed? It Is Usually the Raw Body (or Header Casing)

2026-11-29 · 5 min · Lint Team

Every webhook integration eventually hits the same wall: the provider's console says it sent a signed request, your handler says the signature is invalid, and the payload looks perfect when you print it.

Signature verification is deterministic. If it fails, exactly one of these is true:

  • The bytes you hashed are not the bytes that were signed.
  • The secret you used is not the secret that signed it.
  • The header you read is not the header that was sent.


  • Almost all failures are (1), and almost all of (1) is caused by your framework being helpful.

    Cause 1: the body was parsed before it was verified



    Frameworks deserialize JSON for you. That is convenient everywhere except here.

    The signature is computed over the exact raw bytes on the wire. Once those bytes become a dictionary, re-serializing them produces a different byte sequence with near certainty:

    - Key order may change (many languages preserve insertion order for small maps, then stop).
    - Numbers may reformat: 1.0 becomes 1, 1e3 becomes 1000.0.
    - Unicode may be escaped differently: é as UTF-8 bytes, \u00e9, or a normalized form.
    - Whitespace inside the JSON is gone.

    So the check passes in your unit test (where you serialize with the same library) and fails in production (where the provider serialized with theirs).

    The fix is to capture the raw body before any middleware parses it:


    # Flask — verify raw bytes, parse afterwards
    raw = request.get_data(cache=True)
    sig = request.headers.get("X-Signature", "")
    expected = hmac.new(SECRET, raw, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, sig):
        return "", 401
    payload = json.loads(raw)




    // Express — express.json() must NOT run before this route
    app.post("/webhook", express.raw({ type: "application/json" }), (req, res) => {
      const raw = req.body;                        // Buffer, not object
      const sig = req.get("X-Signature") || "";
      const expected = crypto.createHmac("sha256", SECRET).update(raw).digest("hex");
      if (!crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(sig))) {
        return res.status(401).end();
      }
      const payload = JSON.parse(raw.toString("utf8"));
    });



    Two details worth copying: compare_digest / timingSafeEqual instead of ==, and the raw body captured on the route itself rather than globally.

    Cause 2: the header name is not the header name



    HTTP header names are case-insensitive. Your lookup might not be.

    If your handler does request.headers["Stripe-Signature"] and the proxy in front of you rewrote the header to lowercase — or your framework normalizes to lowercase — the lookup silently returns nothing, and you compare a signature against an empty string.

    Rules that remove the whole class of bug:

    - Read headers through a case-insensitive accessor (req.get(...), headers.get(...)), never a raw dict index.
    - Log the full header dict once when debugging, not the one key you expect.
    - Do not trust a doc's spelling of a header as evidence of the wire format. Reverse proxies and CDNs normalize.

    Cause 3: the secret does not match the environment



    Test-mode and live-mode secrets are different values, and they are usually adjacent in a dashboard. Copying the wrong one produces a 100% failure rate that looks exactly like a code bug.

    You do not need to paste secrets into a ticket to check this. Compare, side by side:

    - length of the value,
    - first four characters,
    - which environment the value was copied from.

    A mismatch in length is definitive. A match in all three is strong evidence you have the right key and should go back to cause 1.

    Rotation adds a second trap: providers often accept an old and a new secret for a window. Your code may verify with only one. During a rotation window, accept both — then remove the old one on a schedule, not "later".

    The 60-second test that tells you which cause it is



    Do not redeploy to test a hypothesis. Verify offline against a captured request:

  • Capture one real request: raw body bytes and all headers, written to a file.
  • Recompute the signature locally with the secret you think is correct.
  • Compare hex strings, character by character.



  • import hmac, hashlib, json
    raw = open("captured_body.bin", "rb").read()       # bytes, not text
    secret = open("/etc/secrets/webhook.key", "rb").read().strip()
    print(hmac.new(secret, raw, hashlib.sha256).hexdigest())
    print(json.load(open("captured_headers.json"))["x-signature"])



    If they match locally but not in production, the difference is in what production hashes — which is cause 1, and it is a plumbing problem, not a crypto problem.

    If they do not match locally with the secret you are sure about, try the other environment's secret — this is cause 3, and it takes ten seconds to confirm.

    A note on what the signature actually protects



    The signature proves the request came from someone holding the secret. It does not prove:

    - that the event is new (replay protection needs a timestamp check inside a tolerance window),
    - that you have not already processed it (that is idempotency, a database constraint),
    - that the amount in the payload is sane (that is business validation against your own order record).

    Verifying the signature is table stakes. Treating it as the whole security model is how integrations end up double-crediting on retry or accepting a replayed request hours later.

    The refactor that prevents all three



    If you are touching this code anyway, make the verification boundary explicit:


    def verified_webhook(request, secret, tolerance_seconds=300):
        raw = request.get_data(cache=True)
        ts = int(request.headers.get("X-Timestamp", 0))
        if abs(time.time() - ts) > tolerance_seconds:
            raise ValueError("stale webhook")        # replay window
        sig = request.headers.get("X-Signature", "")
        expected = hmac.new(secret, f"{ts}.".encode() + raw, hashlib.sha256).hexdigest()
        if not hmac.compare_digest(expected, sig):
            raise ValueError("bad signature")
        return json.loads(raw)                       # parse only after verification



    Three properties, in order: raw bytes in, timestamp checked, parse last. Every failure mode above becomes impossible by construction rather than by remembering.

    ---

    *Working through a messy integration? The free [Lint tools](https://tools.aicreditsapi.com/tools/) include a code explainer that is useful for reading someone else's webhook handler. No subscription — bring your own API key.*
    📌 Prices and tool count in this article may be outdated. Lint now ships 16 tools with Pro at $12/mo, or $60/year. See the current pricing page.
    Try Lint free — no signup, code-aware
    Free · no account needed · open full toolkit →
    L
    Lint Team
    Lint Tools — AI writing for developers

    Stop letting Grammarly break your code

    16 AI tools built for developers. Code-aware parsing.

    Try free — no signup View pricing
    Or upgrade to Pro for 500 checks a day · All tools · No ads

    Need more than free tools?

    Unlock 500 checks a day, larger text capacity, and priority support.

    View pricing → Upgrade Lint — Pro $12/mo or $60/yr
    💬