---
title: "Verify a webhook's signature"
description: "Check the UserLoop-Signature header of every webhook event with the endpoint's secret, in Node.js or Python, and fix the mistakes that make the check fail."
---

> Documentation Index
> Fetch the complete documentation index at: https://docs.userloop.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Verify a webhook's signature

Every webhook event carries a `UserLoop-Signature` header made with your endpoint's signing secret. Check it before you trust an event: it proves the event came from UserLoop, that the body wasn't changed on the way, and that it isn't an old event sent again.

> **Plus plan**
>
> Webhooks are on the Plus plan.

## Before you start

- You need the endpoint's signing secret, which starts `whsec_`. It is shown once, when you add the endpoint or roll its secret: see [Receive responses as they happen](https://docs.userloop.io/developers/webhooks/receive-responses/).
- Your receiver must be able to read the request body exactly as it arrived, as bytes.

## How the signature is made

The header looks like this:

```text
UserLoop-Signature: t=1762855466,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd
```

- `t` is when UserLoop signed the event, in Unix seconds.
- `v1` is the signature: the HMAC-SHA256 of the signed string, keyed with the endpoint's secret, written as 64 lower-case hex characters.
- The signed string is `t`, a full stop, then the raw body: `1762855466.{"id":"evt_…",…}`.
- The key is the whole secret as UTF-8 text, `whsec_` included. Don't decode it.
- For 24 hours after the secret is rolled, the header has two `v1` values, one made with each secret: `t=…,v1=<new>,v1=<old>`. An event is genuine when any `v1` matches.

Each attempt is signed when it is sent, so a retry of the same event has a new `t` and a new `v1`.

To verify an event:

1. Read `t` and every `v1` from the header.
2. Reject the event when `t` is more than 300 seconds (5 minutes) from your clock, in either direction.
3. Compute the HMAC-SHA256 of `<t>.<raw body>` with your secret.
4. Compare it with each `v1` in constant time. Accept the event if one matches.

## Verify in Node.js

This function needs no packages. Save it as `verify.mjs`:

```js
import { createHmac, timingSafeEqual } from "node:crypto";

const TOLERANCE_SECONDS = 300;

/**
 * Checks a UserLoop webhook's signature.
 * rawBody: the request body exactly as received (a Buffer or string), before any JSON parsing.
 * header: the UserLoop-Signature header.
 * secrets: the endpoint's signing secret, or a list of them while you switch after a roll.
 */
export function verifyUserLoopSignature(rawBody, header, secrets, now = Math.floor(Date.now() / 1000)) {
  if (typeof header !== "string") return false;
  let timestamp = null;
  const signatures = [];
  for (const part of header.split(",")) {
    const at = part.indexOf("=");
    if (at <= 0) continue;
    const key = part.slice(0, at).trim();
    const value = part.slice(at + 1).trim();
    if (key === "t" && /^\d{1,12}$/.test(value)) timestamp = Number(value);
    else if (key === "v1" && /^[0-9a-f]{64}$/i.test(value)) signatures.push(Buffer.from(value, "hex"));
  }
  if (timestamp === null || signatures.length === 0) return false;
  if (Math.abs(now - timestamp) > TOLERANCE_SECONDS) return false;

  const body = Buffer.isBuffer(rawBody) ? rawBody : Buffer.from(rawBody, "utf8");
  for (const secret of [secrets].flat()) {
    const expected = createHmac("sha256", secret).update(`${timestamp}.`).update(body).digest();
    if (signatures.some((signature) => timingSafeEqual(signature, expected))) return true;
  }
  return false;
}
```

A complete receiver with Node's own HTTP server, saved as `server.mjs` beside it:

```js
import { createServer } from "node:http";
import { verifyUserLoopSignature } from "./verify.mjs";

const SECRET = process.env.USERLOOP_WEBHOOK_SECRET; // whsec_…
const seen = new Set(); // use your database in production

createServer((req, res) => {
  if (req.method !== "POST") {
    res.writeHead(405).end();
    return;
  }
  const chunks = [];
  req.on("data", (chunk) => chunks.push(chunk));
  req.on("end", () => {
    const rawBody = Buffer.concat(chunks);
    if (!verifyUserLoopSignature(rawBody, req.headers["userloop-signature"], SECRET)) {
      res.writeHead(400).end("Invalid signature");
      return;
    }
    const event = JSON.parse(rawBody.toString("utf8"));
    res.writeHead(200).end(); // answer first, then do the work
    if (seen.has(event.id)) return;
    seen.add(event.id);
    console.log(event.type, event.data);
  });
}).listen(3000);
```

Run it with `USERLOOP_WEBHOOK_SECRET=whsec_… node server.mjs`. With Express, give the webhook route the raw body instead of the JSON parser, then verify `req.body`, which is a `Buffer`:

```js
app.post("/userloop", express.raw({ type: "application/json" }), (req, res) => {
  if (!verifyUserLoopSignature(req.body, req.get("UserLoop-Signature"), process.env.USERLOOP_WEBHOOK_SECRET)) {
    return res.status(400).send("Invalid signature");
  }
  const event = JSON.parse(req.body.toString("utf8"));
  res.sendStatus(200);
  // handle event
});
```

## Verify in Python

Standard library only:

```python
import hashlib
import hmac
import re
import time

TOLERANCE_SECONDS = 300


def verify_userloop_signature(raw_body, header, secrets, now=None):
    """raw_body: the request body as bytes, before any JSON parsing.
    header: the UserLoop-Signature header.
    secrets: the endpoint's signing secret, or a list of them while you switch after a roll."""
    if not header:
        return False
    timestamp, signatures = None, []
    for part in header.split(","):
        key, _, value = part.partition("=")
        key, value = key.strip(), value.strip()
        if key == "t" and re.fullmatch(r"\d{1,12}", value):
            timestamp = int(value)
        elif key == "v1" and re.fullmatch(r"[0-9a-fA-F]{64}", value):
            signatures.append(value.lower())
    if timestamp is None or not signatures:
        return False
    if abs((int(time.time()) if now is None else now) - timestamp) > TOLERANCE_SECONDS:
        return False
    for secret in [secrets] if isinstance(secrets, str) else secrets:
        expected = hmac.new(secret.encode("utf-8"), f"{timestamp}.".encode() + raw_body, hashlib.sha256).hexdigest()
        if any(hmac.compare_digest(signature, expected) for signature in signatures):
            return True
    return False
```

In Flask, pass `request.get_data()`, the body as bytes:

```python
import os
from flask import Flask, abort, request

app = Flask(__name__)
SECRET = os.environ["USERLOOP_WEBHOOK_SECRET"]  # whsec_…


@app.post("/userloop")
def userloop():
    if not verify_userloop_signature(request.get_data(), request.headers.get("UserLoop-Signature"), SECRET):
        abort(400)
    event = request.get_json()
    # store event["id"] and the event, then do the work
    return "", 200
```

## Test your function

Run your function with these values, which use a made-up secret. It must return `true` when `now` is `1762178531`, and `false` when `now` is more than 300 seconds away or when one character of the body changes.

| Input | Value |
| --- | --- |
| Secret | `whsec_test_secret_for_docs_only` |
| Body | `{"id":"evt_test","type":"webhook.test"}` |
| Header | `t=1762178531,v1=c8fee1a46097e81266f900c90c50b043252410999447ab2f38938802b1aa3e7d` |

Then select **Send test** on the endpoint in the dashboard: a real `webhook.test` event signed with your endpoint's secret.

## Switch to a rolled secret

When you select **Roll secret** (or call `POST /webhooks/{webhook_id}/roll-secret`), UserLoop shows the new secret once and signs every event with both secrets for the next 24 hours. Your receiver keeps working with the old secret during that time, so:

1. Store the new secret beside the old one, and verify against both (both functions above take a list).
2. Deploy.
3. Within 24 hours, remove the old secret.

After 24 hours, events carry only the new signature, and a receiver still using only the old secret rejects them.

## Why verification fails

| Cause | What to do |
| --- | --- |
| The body was parsed before verifying. Re-serialising JSON changes spacing, key order or escaping, so the bytes differ from what UserLoop signed. | Verify the raw bytes (`express.raw`, `request.get_data()`), then parse. |
| The body was decoded and re-encoded in another character set, or trimmed. | Use the bytes exactly as received. |
| The secret was decoded, or the `whsec_` prefix removed. | Use the whole secret as text. |
| Only the first `v1` was compared. During a roll, the first value can be the one made with the other secret. | Compare every `v1`. |
| Your server's clock is more than 5 minutes out. | Keep it in sync with NTP. |
| The event was held in a queue before verifying, so `t` is old. | Verify as the request arrives, before queueing it. |
| The header was read with the wrong name. Some frameworks lower-case header names (Node gives `userloop-signature`). | Read the header case-insensitively. |
| The secret belongs to another endpoint, or was rolled more than 24 hours ago. | Each endpoint has its own secret. Roll it again if you lost the current one. |

Answer an event that fails the check with `400` or `401` and don't act on it. Never answer `410`: it removes the endpoint. UserLoop retries a non-`2xx` answer, so a receiver with the wrong secret fails every event until you fix it: see [Retries, duplicates and ordering](https://docs.userloop.io/developers/webhooks/retries-and-duplicates/).

## Related

- [Receive responses as they happen](https://docs.userloop.io/developers/webhooks/receive-responses/)
- [Retries, duplicates and ordering](https://docs.userloop.io/developers/webhooks/retries-and-duplicates/)
- [Webhook events](https://docs.userloop.io/developers/webhooks/events/)

Source: https://docs.userloop.io/developers/webhooks/verify-signatures/index.mdx
