Dev.to Security 🔐 Cybersecurity 👁 2 📖 5 min read

How to Verify a Webhook Signature (HMAC SHA-256), Step by Step

Your webhook endpoint is a public URL. Anyone who finds it can send it a fake order.paid event, and your code will happily mark the order as paid. The signature header is the only thing that proves the request really cam

How to Verify a Webhook Signature (HMAC SHA-256), Step by Step

Your webhook endpoint is a public URL. Anyone who finds it can send it a fake order.paid event, and your code will happily mark the order as paid. The signature header is the only thing that proves the request really came from the provider, so knowing how to verify a webhook signature properly is not optional.

GitHub, Meta and Stripe, like most webhook providers, use the same idea: an HMAC-SHA256 of the request body, keyed with a secret you share. The details differ just enough to break your code. Below is the method with a test value you can check yourself, then the five mistakes behind almost every "signature verification failed" error. This article was written with AI assistance; every example in it was run and checked before publishing.

How a webhook signature works

When you register a webhook, the provider gives you a signing secret. For every delivery it computes HMAC-SHA256(secret, raw request body) and sends the result in a header. HMAC itself is defined in RFC 2104.

On your side you do the same calculation and compare. If the two values match, you know two things: the sender knew the secret, and not a single byte of the body changed on the way. What a match does not prove is that the request is fresh. A captured request can be replayed later with a perfectly valid signature, which is why some providers also sign a timestamp.

Three steps to verify a webhook signature: read the raw body, compute the HMAC, compare in constant time

How to verify a webhook signature by hand

Every implementation comes down to three steps:

  1. Read the raw body exactly as it arrived, as bytes, before any JSON parsing.
  2. Compute the HMAC of those bytes with your signing secret, in the same encoding the provider uses (usually hex).
  3. Compare in constant time with the value from the header.

GitHub publishes a test value in its docs on validating webhook deliveries, which makes it perfect for checking your code. The secret is It's a Secret to Everybody, the payload is Hello, World!, and the X-Hub-Signature-256 header must be:

sha256=757107ea0eb2509fc211221cce984b8a37570b6d7586c22c46f4379c8b043e17

Here is a minimal Python check. We ran it, and it prints True and then False:

import hmac, hashlib

def verify_webhook(secret: str, raw_body: bytes, header: str) -> bool:
    expected = "sha256=" + hmac.new(
        secret.encode("utf-8"), raw_body, hashlib.sha256
    ).hexdigest()
    return hmac.compare_digest(expected, header)

secret = "It's a Secret to Everybody"
body = b"Hello, World!"
header = "sha256=757107ea0eb2509fc211221cce984b8a37570b6d7586c22c46f4379c8b043e17"

print(verify_webhook(secret, body, header))         # True
print(verify_webhook(secret, body + b" ", header))  # False

One extra space at the end of the body and the check fails, which is exactly what you want. The same check in Node.js:

const crypto = require('crypto');

function verifyWebhook(secret, rawBody, header) {
  const expected = 'sha256=' +
    crypto.createHmac('sha256', secret).update(rawBody).digest('hex');
  const a = Buffer.from(expected);
  const b = Buffer.from(header || '');
  // timingSafeEqual throws if lengths differ, so check first
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}

Meta signs its Graph API and WhatsApp webhooks the same way: the Meta webhooks docs say the X-Hub-Signature-256 header carries sha256= plus an HMAC-SHA256 of the payload, keyed with your App Secret.

Five reasons webhook signature verification fails

1. You signed the parsed JSON, not the raw body. Frameworks love to parse the body for you. If you then turn it back into a string, the bytes change. We signed {"event":"order.paid","amount":499} with the secret whsec_demo and got 922c55f2...a0cbd5. Python's json.dumps(json.loads(body)) re-adds spaces after the colons and commas, and the HMAC becomes b24bede2...dd8cc62, with no resemblance to the first. Read the raw bytes (for example express.raw() on the webhook route in Express, or request.get_data() in Flask) and verify before you parse.

2. Hex versus Base64. The same HMAC can be written two ways. For GitHub's test value, hex is 757107ea...043e17 and Base64 is dXEH6g6yUJ/CESIczphLijdXC211hsIsRvQ3nIsEPhc=. Check which one your provider sends and produce the same.

3. The prefix or header format. GitHub and Meta put sha256= in front of the hex value, so either add it to your result or strip it from theirs. Stripe's Stripe-Signature header has a t= timestamp and one or more v1= signatures, and the signed string is the timestamp, a dot and the body, not the body alone. Build the signed string exactly as the docs describe.

4. The wrong secret, or a hidden newline. Test and live endpoints usually have different secrets; Stripe's docs note that the secret printed by its CLI is not the same as the one for a Dashboard endpoint. A secret loaded from a file can also carry a trailing newline. Print its length once and compare it with the one in the dashboard.

5. Comparing with ==. A normal string comparison stops at the first different character, and the time it takes can leak how much of a forged signature was right. Use hmac.compare_digest in Python or crypto.timingSafeEqual in Node.

If the provider sends a timestamp, also reject anything too old. Here is a timestamped check with a five-minute window that we ran with a real value:

import hmac, hashlib, time

def verify_timestamped(secret, raw_body, t, v1, tolerance=300, now=None):
    now = time.time() if now is None else now
    if abs(now - int(t)) > tolerance:
        return False                      # too old: possible replay
    signed = f"{t}.".encode() + raw_body
    expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, v1)

raw = b'{"event":"order.paid","amount":499}'
t = "1796193000"
v1 = "f1a622dd6a36861ec50b2273a398058fca1fd7415ea0dd16b4db30330a2b6dc9"
print(verify_timestamped("whsec_demo", raw, t, v1, now=1796193060))  # True
print(verify_timestamped("whsec_demo", raw, t, v1, now=1796194000))  # False (too old)

FAQs

Is a webhook signature the same as a JWT?
No. A JWT carries its own signed header and claims inside the token. A webhook signature is a separate HMAC of the request body sent in a header. If you work with both, the earlier guide on how to decode a JWT without pasting it into a random website covers the token side.

Should I verify the signature before parsing the JSON?
Yes. Verify the raw bytes first, then parse. Parsing first is the most common reason valid requests get rejected, and acting on unverified JSON defeats the point of the check.

What if the header contains more than one signature?
Accept the request if any one of them matches. Stripe, for example, sends one signature per active secret while you roll a secret, so old and new secrets both work for a while.

More from this series

📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.