---
title: Authentication
slug: 52sY-authentication
icon: {"lucideIcon":"KeyRound"}
createdAt: 2026-11-16T18:01:42.095Z
---

Every webhook EquiDeFi sends is signed with a secret that only you and EquiDeFi know. Checking that signature is how your endpoint knows a request really came from EquiDeFi and wasn't changed on the way. Webhook requests carry no API key, username or password: the signature is the authentication.

This page covers the whole flow: getting your signing secret, what each request contains, how the signature is built, and how to verify it.

## How it works

1. When you create a webhook subscription, EquiDeFi generates a **signing secret** for it. It starts with `whsec_`.
2. For every delivery, EquiDeFi computes an HMAC-SHA256 of the timestamp and the raw request body, using that secret as the key.
3. The result is sent in the `X-Webhook-Signature` header.
4. Your endpoint computes the same HMAC with its copy of the secret. If the two match and the timestamp is recent, the request is genuine.

## Step 1: Get your signing secret

Go to **Offering Settings → Webhooks** and click **Add Webhook**. [Getting Started](https://docs.equidefi.io/getting-started) walks through this screen in detail.

![Add Webhook dialog](https://api.archbee.com/api/optimize/dOqq_NWIQgrNMp0apjZ7I/v4JOWy773-BdHTHNjp0-M_image.png)

As soon as the subscription is created, its signing secret is shown. Copy it and store it with your other server secrets, for example in an `EQUIDEFI_WEBHOOK_SECRET` environment variable.

![Signing Secret dialog](https://api.archbee.com/api/optimize/dOqq_NWIQgrNMp0apjZ7I/a0FqwWzhaRX0L7SDml33i_image.png)

You can see the secret again at any time with the **Signing Secret** button on the subscription's page.

::Image[]{src="https://api.archbee.com/api/optimize/dOqq_NWIQgrNMp0apjZ7I/Z9gM54uEQnpF2ee01K8t0_webhook-subscription-actions.png" size="65" isUploading="false" width="463" height="297" darkWidth="463" darkHeight="297" alt="Webhook subscription page with the Signing Secret and Send Test buttons" showCaption="false"}

:::hint{type="info"}
Each subscription has its own secret. If you have more than one subscription (one per environment or one per endpoint, for example), make sure each endpoint verifies with the secret of the subscription that sends to it.
:::

:::hint{type="warning"}
Use the whole secret as the HMAC key, including the `whsec_` prefix. Treat it like a password: keep it out of source control, client-side code and logs.
:::

## Step 2: Understand the request

Every delivery is an HTTPS `POST` with a JSON body and these headers:

| Header                | Example                                | What it's for                                                                          |
| --------------------- | -------------------------------------- | -------------------------------------------------------------------------------------- |
| `Content-Type`        | `application/json`                     | The body is JSON.                                                                      |
| `User-Agent`          | `EquiDeFi-Webhooks/1`                  | Identifies EquiDeFi's webhook sender.                                                  |
| `X-Webhook-Id`        | `8b1f6c2e-4d3a-4f5b-9c7e-2a1d0e9f8b7c` | The event's unique ID. It stays the same on every retry, so use it to skip duplicates. |
| `X-Webhook-Event`     | `KYC.APPROVED`                         | The event name. See [Events](https://docs.equidefi.io/events).                         |
| `X-Webhook-Timestamp` | `1763308800`                           | When this attempt was signed, in Unix seconds.                                         |
| `X-Webhook-Signature` | `t=1763308800,v1=879b94ee…`            | The timestamp and signature you verify.                                                |

A full request looks like this:

```http
POST /webhooks/equidefi HTTP/1.1
Host: example.com
Content-Type: application/json
User-Agent: EquiDeFi-Webhooks/1
X-Webhook-Id: 8b1f6c2e-4d3a-4f5b-9c7e-2a1d0e9f8b7c
X-Webhook-Event: KYC.APPROVED
X-Webhook-Timestamp: 1763308800
X-Webhook-Signature: t=1763308800,v1=879b94ee58f202a2e87084069d1d53eebe1f60f1ac6ca400588d1b6488310675

{"data":{"id":"8b1f6c2e-4d3a-4f5b-9c7e-2a1d0e9f8b7c","type":"event", ...}}
```

## Step 3: Understand the signature

The `X-Webhook-Signature` header is a comma-separated list of `key=value` parts:

- `t`: the Unix timestamp (seconds) when the request was signed. It matches `X-Webhook-Timestamp`.
- `v1`: the signature, as lowercase hex.

The signature is computed like this:

```plaintext
signed_payload = "{t}.{raw request body}"
v1 = hex( HMAC-SHA256( key = signing secret, message = signed_payload ) )
```

The timestamp is part of what's signed, so nobody can take an old request and change its timestamp to make it look new.

:::hint{type="info"}
The header can contain more than one `v1` value, for example `t=1763308800,v1=abc…,v1=def…`. Accept the request if any one of them matches. That keeps your integration working through a future secret rotation.
:::

## Step 4: Verify every request

For each incoming request:

1. **Read the raw body.** Use the exact bytes you received, before any JSON parsing. A parsed and re-serialized body will almost never match the signature.
2. **Parse&#x20;**`X-Webhook-Signature`**.** Split on `,`, then split each part on the first `=`. Keep the `t` value and every `v1` value.
3. **Check the timestamp.** Reject the request if `t` is more than 5 minutes (300 seconds) away from your server's current time, in either direction.
4. **Compute the expected signature.** HMAC-SHA256 of `{t}.{raw body}` with your signing secret, as hex.
5. **Compare in constant time.** Use your language's constant-time comparison (`timingSafeEqual`, `hmac.compare_digest`, `hash_equals`), never `==`. Accept if any `v1` matches.
6. **Respond.** If verification fails, return `400` and stop. If it passes, process the event and return a `2xx`.

Copy one of these into your webhook endpoint. Each one includes a commented example for a common framework:

:::CodeblockTabs
```javascript
const crypto = require("node:crypto");

const TOLERANCE_SECONDS = 300;

/**
 * Verifies an EquiDeFi webhook. `rawBody` must be the request body exactly as
 * received (a Buffer or string); a re-serialized JSON object will not match.
 */
function verifyEquidefiWebhook(rawBody, signatureHeader, secret, now = Date.now()) {
  if (!signatureHeader) return false;

  // X-Webhook-Signature: t=<unix seconds>,v1=<hex>[,v1=<hex>] (two v1 values during secret rotation)
  let timestamp;
  const signatures = [];
  for (const part of signatureHeader.split(",")) {
    const separator = part.indexOf("=");
    if (separator === -1) continue;
    const key = part.slice(0, separator).trim();
    const value = part.slice(separator + 1).trim();
    if (key === "t" && /^\d+$/.test(value)) timestamp = Number(value);
    else if (key === "v1" && value) signatures.push(value);
  }
  if (timestamp === undefined || signatures.length === 0) return false;

  // Reject stale or future-dated deliveries to limit replays.
  if (Math.abs(Math.floor(now / 1000) - timestamp) > TOLERANCE_SECONDS) return false;

  const expected = crypto.createHmac("sha256", secret).update(`${timestamp}.`).update(rawBody).digest("hex");

  return signatures.some(
    (signature) =>
      signature.length === expected.length &&
      crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected)),
  );
}

module.exports = { verifyEquidefiWebhook };

// Express: read the body raw on this route, then parse it yourself after verifying.
//
// app.post("/webhooks/equidefi", express.raw({ type: "application/json" }), (req, res) => {
//   if (!verifyEquidefiWebhook(req.body, req.get("X-Webhook-Signature"), process.env.EQUIDEFI_WEBHOOK_SECRET)) {
//     return res.sendStatus(400);
//   }
//   const event = JSON.parse(req.body.toString("utf8"));
//   // X-Webhook-Id is the same on every retry of an event; use it to skip duplicates.
//   res.sendStatus(200);
// });

```

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

const TOLERANCE_SECONDS = 300;

/**
 * Verifies an EquiDeFi webhook. `rawBody` must be the request body exactly as
 * received; a re-serialized JSON object will not match the signature.
 */
export function verifyEquidefiWebhook(
  rawBody: string | Buffer,
  signatureHeader: string | undefined,
  secret: string,
  now: number = Date.now(),
): boolean {
  if (!signatureHeader) return false;

  // X-Webhook-Signature: t=<unix seconds>,v1=<hex>[,v1=<hex>] (two v1 values during secret rotation)
  let timestamp: number | undefined;
  const signatures: string[] = [];
  for (const part of signatureHeader.split(",")) {
    const separator = part.indexOf("=");
    if (separator === -1) continue;
    const key = part.slice(0, separator).trim();
    const value = part.slice(separator + 1).trim();
    if (key === "t" && /^\d+$/.test(value)) timestamp = Number(value);
    else if (key === "v1" && value) signatures.push(value);
  }
  if (timestamp === undefined || signatures.length === 0) return false;

  // Reject stale or future-dated deliveries to limit replays.
  if (Math.abs(Math.floor(now / 1000) - timestamp) > TOLERANCE_SECONDS) return false;

  const expected = createHmac("sha256", secret).update(`${timestamp}.`).update(rawBody).digest("hex");

  return signatures.some(
    (signature) =>
      signature.length === expected.length && timingSafeEqual(Buffer.from(signature), Buffer.from(expected)),
  );
}

// Express: read the body raw on this route, then parse it yourself after verifying.
//
// import express from "express";
//
// app.post("/webhooks/equidefi", express.raw({ type: "application/json" }), (req, res) => {
//   const secret = process.env.EQUIDEFI_WEBHOOK_SECRET as string; // whsec_...
//   if (!verifyEquidefiWebhook(req.body, req.get("X-Webhook-Signature"), secret)) {
//     return res.sendStatus(400);
//   }
//   const event = JSON.parse(req.body.toString("utf8"));
//   // X-Webhook-Id is the same on every retry of an event; use it to skip duplicates.
//   res.sendStatus(200);
// });

```

```python
import hashlib
import hmac
import time
from typing import Optional

TOLERANCE_SECONDS = 300

def verify_equidefi_webhook(
    raw_body: bytes, signature_header: Optional[str], secret: str, now: Optional[float] = None
) -> bool:
    """Verifies an EquiDeFi webhook. `raw_body` must be the request body bytes
    exactly as received; a re-serialized JSON object will not match."""
    if not signature_header:
        return False

    # X-Webhook-Signature: t=<unix seconds>,v1=<hex>[,v1=<hex>] (two v1 values during secret rotation)
    timestamp = None
    signatures = []
    for part in signature_header.split(","):
        key, separator, value = part.strip().partition("=")
        if not separator:
            continue
        if key == "t" and value.isdigit():
            timestamp = int(value)
        elif key == "v1" and value:
            signatures.append(value)
    if timestamp is None or not signatures:
        return False

    # Reject stale or future-dated deliveries to limit replays.
    current = int(time.time() if now is None else now)
    if abs(current - timestamp) > TOLERANCE_SECONDS:
        return False

    expected = hmac.new(secret.encode(), f"{timestamp}.".encode() + raw_body, hashlib.sha256).hexdigest()

    return any(hmac.compare_digest(expected, signature) for signature in signatures)


# Flask:
#
# @app.post("/webhooks/equidefi")
# def equidefi_webhook():
#     secret = os.environ["EQUIDEFI_WEBHOOK_SECRET"]  # whsec_...
#     if not verify_equidefi_webhook(request.get_data(), request.headers.get("X-Webhook-Signature"), secret):
#         return "", 400
#     event = request.get_json()
#     # X-Webhook-Id is the same on every retry of an event; use it to skip duplicates.
#     return "", 200

```

```ruby
require "openssl"

module EquidefiWebhook
  TOLERANCE_SECONDS = 300

  # Verifies an EquiDeFi webhook. `raw_body` must be the request body exactly as
  # received; a re-serialized JSON object will not match the signature.
  def self.verify(raw_body, signature_header, secret, now: Time.now.to_i)
    return false if signature_header.nil? || signature_header.empty?

    # X-Webhook-Signature: t=<unix seconds>,v1=<hex>[,v1=<hex>] (two v1 values during secret rotation)
    timestamp = nil
    signatures = []
    signature_header.split(",").each do |part|
      key, value = part.strip.split("=", 2)
      next if value.nil?

      if key == "t" && value.match?(/\A\d+\z/)
        timestamp = value.to_i
      elsif key == "v1" && !value.empty?
        signatures << value
      end
    end
    return false if timestamp.nil? || signatures.empty?

    # Reject stale or future-dated deliveries to limit replays.
    return false if (now - timestamp).abs > TOLERANCE_SECONDS

    # Binary strings, so a body with non-ASCII bytes can't raise an encoding error.
    expected = OpenSSL::HMAC.hexdigest("SHA256", secret, "#{timestamp}.".b + raw_body.b)

    signatures.any? { |signature| secure_compare(expected, signature) }
  end

  def self.secure_compare(a, b)
    return false unless a.bytesize == b.bytesize

    result = 0
    a.bytes.zip(b.bytes) { |x, y| result |= x ^ y }
    result.zero?
  end
end

# Rails:
#
#   def equidefi
#     secret = ENV.fetch("EQUIDEFI_WEBHOOK_SECRET") # whsec_...
#     unless EquidefiWebhook.verify(request.raw_post, request.headers["X-Webhook-Signature"], secret)
#       return head :bad_request
#     end
#     event = JSON.parse(request.raw_post)
#     # X-Webhook-Id is the same on every retry of an event; use it to skip duplicates.
#     head :ok
#   end
#
# Sinatra: use `request.body.read` as the raw body.

```

```php
<?php

const EQUIDEFI_WEBHOOK_TOLERANCE_SECONDS = 300;

/**
 * Verifies an EquiDeFi webhook. $rawBody must be the request body exactly as
 * received (file_get_contents('php://input')); a re-encoded JSON array will not match.
 */
function verify_equidefi_webhook(string $rawBody, ?string $signatureHeader, string $secret, ?int $now = null): bool
{
    if ($signatureHeader === null || $signatureHeader === '') {
        return false;
    }

    // X-Webhook-Signature: t=<unix seconds>,v1=<hex>[,v1=<hex>] (two v1 values during secret rotation)
    $timestamp = null;
    $signatures = [];
    foreach (explode(',', $signatureHeader) as $part) {
        $pair = explode('=', trim($part), 2);
        if (count($pair) !== 2) {
            continue;
        }
        [$key, $value] = $pair;
        if ($key === 't' && ctype_digit($value)) {
            $timestamp = (int) $value;
        } elseif ($key === 'v1' && $value !== '') {
            $signatures[] = $value;
        }
    }
    if ($timestamp === null || count($signatures) === 0) {
        return false;
    }

    // Reject stale or future-dated deliveries to limit replays.
    if (abs(($now ?? time()) - $timestamp) > EQUIDEFI_WEBHOOK_TOLERANCE_SECONDS) {
        return false;
    }

    $expected = hash_hmac('sha256', $timestamp . '.' . $rawBody, $secret);

    $verified = false;
    foreach ($signatures as $signature) {
        // hash_equals is constant-time.
        if (hash_equals($expected, $signature)) {
            $verified = true;
        }
    }

    return $verified;
}

// Plain PHP:
//
// $rawBody = file_get_contents('php://input');
// $secret = getenv('EQUIDEFI_WEBHOOK_SECRET'); // whsec_...
// if (!verify_equidefi_webhook($rawBody, $_SERVER['HTTP_X_WEBHOOK_SIGNATURE'] ?? null, $secret)) {
//     http_response_code(400);
//     exit;
// }
// $event = json_decode($rawBody, true);
// // X-Webhook-Id ($_SERVER['HTTP_X_WEBHOOK_ID']) is the same on every retry of an event; use it to skip duplicates.
// http_response_code(200);
//
// Laravel: verify_equidefi_webhook($request->getContent(), $request->header('X-Webhook-Signature'), $secret)

```
:::

## Step 5: Protect against replays and duplicates

- **Replays.** The 5-minute timestamp check stops someone from capturing a genuine request and sending it to you again later. Keep your server clock in sync (NTP), or genuine requests may be rejected.
- **Duplicates.** If your endpoint fails or times out, EquiDeFi sends the same event again. Every retry is signed again with a new timestamp, but `X-Webhook-Id` stays the same. Record the IDs you've processed and skip any you've already seen.

## Step 6: Respond

- Return any `2xx` to tell EquiDeFi the delivery succeeded. Anything else, including redirects, counts as a failure.
- Respond within 15 seconds. If you have slow work to do, store the event, return `200`, and process it afterwards.
- Return `400` when verification fails, so the failure shows in your delivery log.

See [Retry Behavior](https://docs.equidefi.io/retry-behavior) for timeouts, the retry schedule and the delivery log.

## Test your integration

### Use Send Test

Open your subscription and click **Send Test**. To try a different URL before you save it, click **Edit** and use **Send Test** in the dialog. EquiDeFi sends a signed `TEST.SENT` event with the subscription's real signing secret and shows you what your endpoint returned. A test contains no investor data and doesn't appear in the delivery log.

::Image[]{src="https://api.archbee.com/api/optimize/dOqq_NWIQgrNMp0apjZ7I/2tn91Iz9P3GrluW2UFdwf_webhook-send-test-result.png" size="90" isUploading="false" width="640" height="618" darkWidth="640" darkHeight="618" alt="Send Test result showing a passed delivery" showCaption="false"}

A `2xx` means your endpoint accepted the signed request. A `400` here means your verification is rejecting a genuine request; see Troubleshooting below.

### Check your code against a known example

Use these values in a unit test. Your code should compute exactly this signature:

| Input           | Value                                                                                                                 |
| --------------- | --------------------------------------------------------------------------------------------------------------------- |
| Secret          | `whsec_7f9a1c3e5b2d4f6a8c0e1b3d5f7a9c2e4b6d8f0a1c3e5b7d9f2a4c6e8b0d1f3a`                                              |
| Timestamp (`t`) | `1763308800`                                                                                                          |
| Raw body        | `{"data":{"id":"8b1f6c2e-4d3a-4f5b-9c7e-2a1d0e9f8b7c","type":"event","attributes":{"event":"TEST","action":"SENT"}}}` |
| Expected `v1`   | `879b94ee58f202a2e87084069d1d53eebe1f60f1ac6ca400588d1b6488310675`                                                    |

Or check it from a terminal:

```bash
printf '%s' '1763308800.{"data":{"id":"8b1f6c2e-4d3a-4f5b-9c7e-2a1d0e9f8b7c","type":"event","attributes":{"event":"TEST","action":"SENT"}}}' \
  | openssl dgst -sha256 -hmac 'whsec_7f9a1c3e5b2d4f6a8c0e1b3d5f7a9c2e4b6d8f0a1c3e5b7d9f2a4c6e8b0d1f3a'
```

:::hint{type="info"}
This timestamp is in the past, so pass a matching "now" into your function when you run this test. The examples above all accept one: `1763308800000` in milliseconds for JavaScript and TypeScript, `1763308800` in seconds for Python, Ruby and PHP.
:::

## Troubleshooting

If your endpoint rejects requests that came from EquiDeFi, check these first:

| Symptom                                | Likely cause                                           | Fix                                                                                                                          |
| -------------------------------------- | ------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------- |
| Signature never matches                | Your framework parsed the JSON before you verified it. | Read the raw body on your webhook route: `express.raw()`, `request.get_data()`, `request.raw_post` or `php://input`.         |
| Signature never matches                | Wrong secret.                                          | Copy the secret from this subscription's **Signing Secret** button, including `whsec_`, with no extra spaces or line breaks. |
| Signature never matches                | You signed only the body.                              | The signed message is `{t}.{body}`, with a dot between them.                                                                 |
| Works locally, fails in production     | A proxy or middleware changes the body.                | Make sure nothing re-encodes, pretty-prints or decompresses the body before your check.                                      |
| Some requests fail the timestamp check | Your server clock is off.                              | Sync your clock with NTP. The allowed window is 5 minutes.                                                                   |
| Send Test shows a `3xx`                | Your URL redirects.                                    | Use the final URL. EquiDeFi doesn't follow redirects.                                                                        |

## Related

- [Getting Started](https://docs.equidefi.io/getting-started): create and manage webhook subscriptions.
- [Best Practices](https://docs.equidefi.io/best-practices): general advice for webhook consumers.
- [Retry Behavior](https://docs.equidefi.io/retry-behavior): timeouts, retries and the delivery log.
- [Events](https://docs.equidefi.io/events): every event and its payload.
