Verify the HMAC signature of a webhook

Stripe, GitHub and Shopify sign their webhooks with HMAC. Here is what the signature guarantees, and the mistakes that make verification fail.

What an HMAC signature proves

A webhook is an HTTP request a service sends to your server when something happens: a successful payment, a push to a repository, a new order. Your endpoint is public, so anyone can send it a request that looks like a webhook. The signature is how you tell them apart.

During setup, you and the service agree on a shared secret key. With every delivery, the service computes HMAC(key, request body) and puts the result in a header. Your server runs the same calculation with its copy of the key and compares. If the two values match, two things are established:

  • origin: only someone holding the key can produce that signature;
  • integrity: changing a single byte of the body gives a completely different signature.

HMAC is not encryption: the body travels in readable form, and HTTPS is what keeps it private in transit. The two work together.

What the headers look like

Each service picks its own header and format. Two widespread examples:

X-Hub-Signature-256: sha256=5bdcc146bf60754e…
Stripe-Signature: t=1700000000,v1=7d1e5b9c3a…

GitHub signs the body alone with HMAC-SHA-256 and writes the result in hex, prefixed with sha256=. Stripe signs the timestamp t, a dot, then the body, and puts the hex signature in v1. Other services use Base64. The service's documentation always specifies three things: what is signed, the algorithm, and how the signature is written.

Compute it on the raw body, before any parsing

The signature covers bytes, not a JSON object. Yet most frameworks read the body and turn it into an object before your code runs. Serializing that object again almost never gives back the same bytes: key order, whitespace, escaped non-ASCII characters, rewritten numbers. Verification then fails on a perfectly genuine message.

The rule fits in one sentence: grab the raw body, verify the signature against it, and only then parse the JSON. Each stack has its own way to get those bytes:

StackRaw bodyConstant-time comparison
Node.js (Express)express.raw()crypto.timingSafeEqual
Python (Flask)request.get_data()hmac.compare_digest
PHPfile_get_contents('php://input')hash_equals
.NET (ASP.NET Core)Request.Body, read before model bindingCryptographicOperations.FixedTimeEquals

Compare in constant time

An ordinary comparison, == or equals, stops at the first character that differs. It therefore answers slightly faster when the beginning is wrong than when it is right. By measuring those gaps over a large number of requests, an attacker could in theory guess a valid signature one character at a time, without ever knowing the key.

The functions in the table above always go through the full length before answering, so their timing reveals nothing about where a difference lies. They ship with the standard library; use them every time you compare a signature.

Example in Node.js

import crypto from 'node:crypto';
import express from 'express';

const app = express();
const secret = process.env.WEBHOOK_SECRET;

// express.raw() keeps the body as a Buffer, byte for byte
app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => {
  const expected = Buffer.from(
    'sha256=' + crypto.createHmac('sha256', secret).update(req.body).digest('hex'));
  const received = Buffer.from(req.get('X-Hub-Signature-256') ?? '');

  // timingSafeEqual requires two buffers of the same length
  if (received.length !== expected.length || !crypto.timingSafeEqual(received, expected)) {
    return res.sendStatus(401);
  }

  const event = JSON.parse(req.body.toString('utf8'));
  // … handle the event
  res.sendStatus(204);
});

Example in Python

import hashlib, hmac, json, os
from flask import Flask, abort, request

app = Flask(__name__)
SECRET = os.environ["WEBHOOK_SECRET"].encode()

@app.post("/webhook")
def webhook():
    body = request.get_data()  # raw bytes, before any parsing
    expected = b"sha256=" + hmac.new(SECRET, body, hashlib.sha256).hexdigest().encode()
    received = request.headers.get("X-Hub-Signature-256", "").encode()

    if not hmac.compare_digest(expected, received):
        abort(401)

    event = json.loads(body)
    # … handle the event
    return "", 204

Both examples follow GitHub's format. For another service, only the header name, the prefix and, where needed, the encoding change (digest('base64') in Node.js, base64.b64encode(…digest()) in Python).

Timestamps against replay attacks

A valid signature stays valid for as long as the key does not change. Someone who intercepts a signed webhook could send it again later, unchanged: that is a replay. When the service includes a timestamp in what it signs, as Stripe does with t, check it:

  1. rebuild the signed message exactly as the documentation describes (for Stripe, t + "." + raw body);
  2. verify the signature on that message;
  3. reject the request if the timestamp is too far from your clock. Stripe's libraries allow 5 minutes by default.

Since the timestamp is signed, it cannot be made more recent without breaking the signature. On top of that, recording the ID of each processed event lets you skip duplicates, which also covers legitimate retries from the service after a timeout. When the service provides an official library, its verification function does all of this for you.

Rotating the key

Change the key when someone who knew it leaves, after a possible leak, or on a regular schedule. To lose no events during the switch:

  1. generate the new key and configure it on the receiving side, alongside the old one;
  2. accept a request if its signature matches either key;
  3. switch the sender to the new key;
  4. remove the old key once the last event signed with it has arrived.

Some services handle this overlap themselves and send two signatures in the meantime. To create the new key, the kit's HMAC generator draws 32 random bytes in your browser and lets you test a signature with it straight away.

Sharing the key

The key has to exist in two places: with the sender and with the receiver. It often travels from one team to another, or from a partner to you, during setup. That is the moment it tends to end up in a ticket, an email or a chat, readable by anyone with access, for a long time.

With “Send with onlyU”, the tool passes the key to onlyU tab to tab in your browser, never in an address and never through the kit's server. onlyU encrypts it in your browser and creates a link your recipient opens only once, valid for 24 hours, after which the link disappears. It is free, with no sign-up. Once the key is in place on both ends, store it in each platform's environment variables or secrets vault, like any secret key.