All articles Integration

How to Verify Webhook HMAC Signatures

Developer in a dark studio handling a translucent blue stream of light between their hands

Your integration works until someone posts a fake event to your endpoint. The fix is not more middleware: it is to verify webhook HMAC signatures on every request, before your handler parses a field. An HMAC binds the payload to a secret only you and the sender hold, so a tampered body or a forged delivery fails the comparison instead of writing a fake decision into your system.

The mechanics are simple; the failure modes are not. Teams get the digest right and still compare with ==, verify a re-serialized body, or leave a replay window open. A forged allow or block event is an account-takeover vector, not a cosmetic bug. Below: the four checks that matter, with Node and Python code for Prynt Automate and Prynt Identify webhooks.

Treat verification as a pipeline: signature, timestamp, idempotency, then business logic. Each step is cheap and each one removes a class of incident.

Know what the header signs

Signed webhooks arrive in two shapes: a timestamp in its own header with the signature over the body, or one composite header that carries both. Prynt uses the composite kind — X-Prynt-Signature carries a timestamp and a sha256 hex digest computed over the timestamp, a dot, and the raw body. Confirm the exact composition in our docs and pin it in a comment next to your handler.

Verify the raw bytes, not a re-serialized object

JSON parsers reorder keys and normalize numbers, so verifying JSON.stringify(parsed) can match your test payloads and fail on real traffic. Register a raw body parser for the webhook route and parse JSON only after the signature passes: express.raw({ type: "application/json" }) in Express, await request.body() in FastAPI, await req.text() in a Next.js route handler.

Compare in constant time

A plain == returns as soon as two bytes differ, which leaks how much of the digest was correct. It is a small leak over a network, and the fix is free: crypto.timingSafeEqual in Node and hmac.compare_digest in Python compare in time independent of the input.

Glass-like seal with blue edge lighting crossed by thin threads of light

import crypto from "node:crypto";

const parts = Object.fromEntries(
  req.get("X-Prynt-Signature").split(",").map((p) => p.split("=", 2))
);
const expected = crypto
  .createHmac("sha256", process.env.PRYNT_WEBHOOK_SECRET)
  .update(`${parts.t}.${req.body}`) // req.body is the raw Buffer
  .digest("hex");
const a = Buffer.from(expected, "hex");
const b = Buffer.from(parts.v1, "hex");
if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) {
  return res.status(401).json({ error: "bad_signature" });
}
parts = dict(p.split("=", 1) for p in
             request.headers["x-prynt-signature"].split(","))
msg = f"{parts['t']}.".encode() + await request.body()
expected = hmac.new(SECRET.encode(), msg, hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, parts["v1"]):
    return Response(status_code=401)

Check the buffer lengths before calling timingSafeEqual, which throws on a mismatch, and return the same generic 401 in every failure branch.

Close the replay window

A valid signature is not a fresh signature. Anyone who captures a delivery can resend it byte for byte and the HMAC still passes. Reject timestamps outside a short window — five minutes is a common choice — and check both directions so a clock far in the future fails too. Keep your server on NTP: a drifting clock turns valid deliveries into 401s and tempts you to disable the check. Log rejected timestamps with the event ID; a burst of them usually means a clock problem, not an attack.

Inside the window you need deduplication. Store the event ID from the payload behind a unique index with a TTL longer than your retry horizon, and treat the second arrival as success: insert first, act second, and exit with 200 when the insert conflicts.

Keep retries and slow work out of the webhook path

Automate retries failed runs and keeps a run log, so your endpoint will see the same event more than once. Do the minimum before responding: verify, persist, enqueue, return 200. Work done inline will time out under load and get retried.

Two engineers in a dark room comparing two equal beams of light side by side

Pick status codes deliberately. 2xx means stored, do not resend. 5xx means try again. 4xx on a genuine event drops it, so reserve that for authentication failures and malformed payloads. Log the event ID and your decision — never the secret, never the full signature. The same logic works in the other direction: when you call another API, send an idempotency key so a retried call cannot charge twice.

Test the failure paths, not just the happy one

Add these cases to your suite before the first production delivery:

  • Body changed by one byte returns 401.
  • Correct body, wrong secret returns 401.
  • Missing or malformed header returns 401.
  • Timestamp six minutes old, or six minutes ahead, is rejected.
  • The same event ID twice produces one write and two 200s.
  • A valid signature with an unknown event type is stored and ignored.

Run the suite against a test secret in CI, and repeat the happy path once after deploy from a script rather than by hand.

FAQ

Person standing before concentric blue rings of light, one ring glowing brighter

Does HMAC verification replace HTTPS?

No. TLS protects the payload in transit; the HMAC proves the sender knew the shared secret and that the bytes were not altered after signing. You need both.

Where should the signing secret live?

In a secret manager or an environment variable injected at runtime, one secret per endpoint. Rotate with an overlap where you accept the old and new secret, and log which one matched so you know when to retire the old one.

What should I return when verification fails?

A generic 401, with no echo of the payload and no hint about which check failed. Only verified events should reach your business logic or your logs.

If you would rather not hand-roll signing for every new workflow, Prynt Automate signs each outbound webhook, retries failed runs and keeps a run log. Read the header format in the docs and start on the free tier at pryntid.com.

Try it free

Prynt is device intelligence with a free plan: 5,000 identifications a month, visitor IDs with confidence and bot detection — no credit card. Upgrade to Pro for VPN, proxy, tampering and behavioral signals.

Keep reading