Skip to main content

Verifying Webhook Signatures

Anyone can POST JSON to a public URL. The signature is what proves a delivery came from Budget Thing, so verify every request before you act on it.

The scheme​

Budget Thing signs the delivery with HMAC-SHA256, keyed on the endpoint's signing secret. The signed message is the delivery id, the timestamp and the exact raw request body, joined with full stops:

<delivery-id>.<unix-timestamp>.<raw-request-body>
signature = hex( HMAC_SHA256( signing_secret, deliveryId + "." + timestamp + "." + rawBody ) )

The result is lower-case hexadecimal, sent with a v1= scheme prefix:

BudgetThing-Webhook-Id: whd_4Bn8Rk2Xm7Qd5Vz1Lp9Wsk
BudgetThing-Webhook-Timestamp: 1789499532
BudgetThing-Webhook-Signature: v1=3f0b2c9d7e5a1846bd4c0f7a2e9b6d13c8a5f2e4b7d90c1a6f3e8b5d2c7a4091
DetailValue
AlgorithmHMAC-SHA256
KeyThe signing secret, including its whsec_ prefix, exactly as issued
MessagedeliveryId + "." + timestamp + "." + rawBody
EncodingLower-case hex
HeaderBudgetThing-Webhook-Signature, values prefixed v1=
Multiple valuesSpace-separated during a secret rotation
Never re-serialize the body before verifying

Read the raw bytes of the request body and sign those. If you parse the JSON and re-encode it — which most frameworks do implicitly when you touch a parsed body — key order, spacing and number formatting change, the bytes differ from what was signed, and every signature fails. Parse the JSON after verification, from the same bytes you verified.

In practice this means disabling the automatic JSON body parser on the webhook route, or reading the raw body before it runs.

The procedure​

  1. Read the raw request body bytes, before any JSON parsing.
  2. Read BudgetThing-Webhook-Id.
  3. Read BudgetThing-Webhook-Timestamp.
  4. Reject the request if the timestamp is outside your tolerance — five minutes is a sensible window.
  5. Build the message deliveryId.timestamp.rawBody.
  6. Compute HMAC-SHA256 with the signing secret and hex-encode it.
  7. Compare it against each v1= value in the signature header, using a constant-time comparison. Accept if any matches.
  8. Parse the JSON, then skip the event if you have already processed its id.
  9. Queue the work and answer 2xx.

Two secrets are in play during the 24 hours after a rotation: the header then carries two space-separated signatures, one per valid secret. A receiver that checks every v1= value against every secret it currently trusts survives a rotation without downtime — which is why all three examples below take a list of secrets.

What to answer when verification fails

Answer 400 and do not process the request. Budget Thing treats it as a failed attempt and retries, so a genuine delivery you rejected because of a misconfiguration is not lost — and the failures are visible in the delivery history. Never answer 2xx to a request you could not verify.

JavaScript / Node.js​

Standard library only — node:crypto has everything needed.

import crypto from 'node:crypto';

const TOLERANCE_SECONDS = 300;

/**
* @param rawBody Buffer — the untouched request body
* @param headers the request headers (lower-cased keys, as Node provides)
* @param secrets every signing secret currently trusted, newest first
*/
export function verifyWebhook(rawBody, headers, secrets) {
const deliveryId = headers['budgetthing-webhook-id'];
const timestamp = headers['budgetthing-webhook-timestamp'];
const signatureHeader = headers['budgetthing-webhook-signature'];

if (!deliveryId || !timestamp || !signatureHeader) return false;

const sentAt = Number(timestamp);
if (!Number.isInteger(sentAt)) return false;
const now = Math.floor(Date.now() / 1000);
if (Math.abs(now - sentAt) > TOLERANCE_SECONDS) return false;

const signedMessage = Buffer.concat([
Buffer.from(`${deliveryId}.${timestamp}.`, 'utf8'),
rawBody,
]);

const received = signatureHeader
.split(' ')
.filter((part) => part.startsWith('v1='))
.map((part) => part.slice(3));

return secrets.some((secret) => {
const expected = crypto
.createHmac('sha256', secret)
.update(signedMessage)
.digest('hex');
const expectedBytes = Buffer.from(expected, 'utf8');

return received.some((candidate) => {
const candidateBytes = Buffer.from(candidate, 'utf8');
return (
candidateBytes.length === expectedBytes.length &&
crypto.timingSafeEqual(candidateBytes, expectedBytes)
);
});
});
}

With Express, the route needs the raw body, so give it the raw parser instead of the JSON one:

import express from 'express';

const app = express();
const secrets = [process.env.BUDGETTHING_WEBHOOK_SECRET];

app.post(
'/webhooks/budgetthing',
express.raw({type: 'application/json'}),
async (req, res) => {
if (!verifyWebhook(req.body, req.headers, secrets)) {
return res.status(400).send('invalid signature');
}

const event = JSON.parse(req.body.toString('utf8'));

if (await alreadyProcessed(event.id)) {
return res.sendStatus(200); // a duplicate delivery of a handled event
}

await enqueue(event); // do the real work outside the request
res.sendStatus(200);
},
);

Python​

import hashlib
import hmac
import time

TOLERANCE_SECONDS = 300


def verify_webhook(raw_body: bytes, headers, secrets: list[str]) -> bool:
"""raw_body must be the untouched request body; secrets are the signing
secrets currently trusted, newest first."""
delivery_id = headers.get("BudgetThing-Webhook-Id")
timestamp = headers.get("BudgetThing-Webhook-Timestamp")
signature_header = headers.get("BudgetThing-Webhook-Signature")

if not delivery_id or not timestamp or not signature_header:
return False

try:
sent_at = int(timestamp)
except ValueError:
return False

if abs(int(time.time()) - sent_at) > TOLERANCE_SECONDS:
return False

signed_message = f"{delivery_id}.{timestamp}.".encode() + raw_body

received = [
part[len("v1="):]
for part in signature_header.split(" ")
if part.startswith("v1=")
]

for secret in secrets:
expected = hmac.new(
secret.encode(), signed_message, hashlib.sha256
).hexdigest()
if any(hmac.compare_digest(candidate, expected) for candidate in received):
return True

return False

A Flask route, reading the body before anything parses it:

import json
import os

from flask import Flask, request

app = Flask(__name__)
SECRETS = [os.environ["BUDGETTHING_WEBHOOK_SECRET"]]


@app.post("/webhooks/budgetthing")
def receive_webhook():
raw_body = request.get_data() # bytes, exactly as received

if not verify_webhook(raw_body, request.headers, SECRETS):
return "invalid signature", 400

event = json.loads(raw_body)

if already_processed(event["id"]):
return "", 200

enqueue(event)
return "", 200

Go​

package webhook

import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"net/http"
"strconv"
"strings"
"time"
)

const tolerance = 5 * time.Minute

// Verify reports whether rawBody was signed by one of the trusted secrets.
// rawBody must be the untouched request body.
func Verify(rawBody []byte, header http.Header, secrets []string) bool {
deliveryID := header.Get("BudgetThing-Webhook-Id")
timestamp := header.Get("BudgetThing-Webhook-Timestamp")
signatureHeader := header.Get("BudgetThing-Webhook-Signature")

if deliveryID == "" || timestamp == "" || signatureHeader == "" {
return false
}

sentAt, err := strconv.ParseInt(timestamp, 10, 64)
if err != nil {
return false
}
if skew := time.Since(time.Unix(sentAt, 0)); skew > tolerance || skew < -tolerance {
return false
}

signedMessage := make([]byte, 0, len(deliveryID)+len(timestamp)+len(rawBody)+2)
signedMessage = append(signedMessage, deliveryID...)
signedMessage = append(signedMessage, '.')
signedMessage = append(signedMessage, timestamp...)
signedMessage = append(signedMessage, '.')
signedMessage = append(signedMessage, rawBody...)

for _, secret := range secrets {
mac := hmac.New(sha256.New, []byte(secret))
mac.Write(signedMessage)
expected := []byte(hex.EncodeToString(mac.Sum(nil)))

for _, part := range strings.Fields(signatureHeader) {
candidate, ok := strings.CutPrefix(part, "v1=")
if !ok {
continue
}
if hmac.Equal([]byte(candidate), expected) {
return true
}
}
}

return false
}

The handler reads the body once and works from those bytes:

// additionally imports "encoding/json" and "io"

const maxBodyBytes = 1 << 20 // 1 MiB is ample for an event payload

func Handler(secrets []string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
rawBody, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxBodyBytes))
if err != nil {
http.Error(w, "unreadable body", http.StatusBadRequest)
return
}

if !Verify(rawBody, r.Header, secrets) {
http.Error(w, "invalid signature", http.StatusBadRequest)
return
}

var envelope struct {
ID string `json:"id"`
Type string `json:"type"`
}
if err := json.Unmarshal(rawBody, &envelope); err != nil {
http.Error(w, "malformed payload", http.StatusBadRequest)
return
}

if processed(envelope.ID) {
w.WriteHeader(http.StatusOK)
return
}

enqueue(envelope.ID, envelope.Type, rawBody)
w.WriteHeader(http.StatusOK)
}
}

When verification fails​

Work through these in order:

SymptomLikely cause
Every signature fails, payload looks fineThe body was parsed and re-serialized before signing. Verify the raw bytes.
Every signature fails after a rotationThe receiver trusts only one secret. Accept every v1= value against every secret you hold.
Signatures fail intermittentlyTwo endpoints share one route and one secret. Each endpoint has its own secret; route by endpoint or store the secret per endpoint.
Signatures fail, timestamps rejectedThe receiver's clock has drifted. Synchronise it; the tolerance is small on purpose.
The header is missing entirelySomething between Budget Thing and your application dropped it. Check that your proxy forwards BudgetThing-* headers.
Only some deliveries failThe signed message was built from the wrong parts. It is deliveryId.timestamp.rawBody — all three, in that order.

The delivery history shows the exact request headers and payload for any delivery, which is the quickest way to compare what was sent with what your receiver saw.

Next​