Step 1 of 6Store the signing secret on your server

Verify webhook signatures in Node, PHP, Python, Java and Go

After this guide, your server accepts only webhooks that Strait signed in the last 5 minutes, and refuses replayed or edited ones, in Node, PHP, Python, Java or Go.

On this page 8
  1. 1. Store the signing secret on your server
  2. 2. Know exactly what is signed
  3. 3. Add the verifier for your language
  4. 4. Call it with the raw body in your framework
  5. 5. Send a test event
  6. 6. Ignore repeats
  7. Common errors
  8. Next steps
Time
About 20 minutes
You need
A webhook in Dashboard → Settings → Webhooks, its signing secret, and a public https endpoint on your server
Works on
Node 18+ (Express), PHP 8.1+ (Laravel or plain PHP), Python 3.8+ (Flask, Django, FastAPI), Java 17+ (Spring Boot), Go 1.20+ (net/http)

Every delivery is an HTTPS POST with a JSON body and a X-Strait-Signature header. Anyone can send your endpoint a POST, so check the signature before you trust the body. The verifiers on this page use only each language's standard library, and every one of them is tested in our build against signatures made by our server's own signing code. For events, retries and the delivery log, see Webhooks.

1. Store the signing secret on your server

Copy the signing secret when you create the webhook in Dashboard → Settings → Webhooks. It's shown once. Put it in your server's environment as WEBHOOK_SECRET, next to your secret API key, and never in an app or a website.

You should see: WEBHOOK_SECRET set in the environment your webhook handler runs in (for example echo ${WEBHOOK_SECRET:0:5} prints its first characters).

2. Know exactly what is signed

The header looks like this:

Code
X-Strait-Signature: t=1800000000,v1=adf19a16865985b0891b0e7e4f6770e17d6bdd6462d897848f5adb661c4381bb
  • t is the Unix time in seconds when we signed this attempt.
  • v1 is the lowercase hex HMAC-SHA256 of the string <t>.<raw body>: the value of t, a full stop, then the exact bytes of the request body, keyed with your signing secret.

So your check is: split the header on , and each part on the first =, refuse a t more than 300 seconds from your clock (either way), compute the HMAC yourself and compare it with v1 in constant time. Every retry is signed again with a fresh t.

Use this vector to test your code before any real delivery:

Input Value
Secret whsec
Raw body {"a":1}
t 1800000000
Expected header t=1800000000,v1=adf19a16865985b0891b0e7e4f6770e17d6bdd6462d897848f5adb661c4381bb

You should see: the same v1 from your language's HMAC function, for example printf '%s' '1800000000.{"a":1}' | openssl dgst -sha256 -hmac whsec prints adf19a16…381bb.

3. Add the verifier for your language

On Node you can skip the hand-written verifier: @straitlink/node 0.6.5 and later has verifyWebhook(rawBody, headers, secret), which makes this exact check (how).

Each function takes the secret, the raw body, the header and an optional "now" (so you can test it with the vector above), and returns true or false.

Node: strait-signature.mjs
import { createHmac, timingSafeEqual } from 'node:crypto';

const TOLERANCE_SECONDS = 300;

/** True when `header` is a valid X-Strait-Signature for `rawBody` (a Buffer or string). */
export function verifyStraitSignature(secret, rawBody, header, nowSeconds = Date.now() / 1000) {
  if (!header) return false;
  const parts = new Map(header.split(',').map((p) => {
    const i = p.indexOf('=');
    return [p.slice(0, i).trim(), p.slice(i + 1).trim()];
  }));
  const t = parts.get('t') ?? '';
  const v1 = parts.get('v1') ?? '';
  if (!/^\d+$/.test(t) || !v1) return false;
  if (Math.abs(nowSeconds - Number(t)) > TOLERANCE_SECONDS) return false;
  const expected = Buffer.from(createHmac('sha256', secret).update(`${t}.`).update(rawBody).digest('hex'));
  const given = Buffer.from(v1);
  return expected.length === given.length && timingSafeEqual(expected, given);
}
PHP: StraitSignature.php
<?php

function verify_strait_signature(string $secret, string $rawBody, ?string $header, ?int $now = null): bool
{
    if ($header === null || $header === '') {
        return false;
    }
    $parts = [];
    foreach (explode(',', $header) as $part) {
        $pair = explode('=', trim($part), 2);
        if (count($pair) === 2) {
            $parts[$pair[0]] = $pair[1];
        }
    }
    $t = $parts['t'] ?? '';
    $v1 = $parts['v1'] ?? '';
    if (preg_match('/^\d+$/D', $t) !== 1 || $v1 === '') {
        return false;
    }
    if (abs(($now ?? time()) - (int) $t) > 300) {
        return false;
    }
    $expected = hash_hmac('sha256', $t . '.' . $rawBody, $secret);
    return hash_equals($expected, $v1);
}
Python: strait_signature.py
import hashlib
import hmac
import time
from typing import Optional

TOLERANCE_SECONDS = 300


def verify_strait_signature(secret: str, raw_body: bytes, header: Optional[str], now: Optional[float] = None) -> bool:
    if not header:
        return False
    parts = dict(p.strip().split("=", 1) for p in header.split(",") if "=" in p)
    t, v1 = parts.get("t", ""), parts.get("v1", "")
    if not (t.isascii() and t.isdigit()) or not v1:
        return False
    if abs((time.time() if now is None else now) - int(t)) > TOLERANCE_SECONDS:
        return False
    expected = hmac.new(secret.encode(), t.encode() + b"." + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, v1)
Java: StraitSignature.java
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.HexFormat;
import java.util.Map;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public final class StraitSignature {
    private static final long TOLERANCE_SECONDS = 300;

    private StraitSignature() {}

    public static boolean verify(String secret, byte[] rawBody, String header) {
        return verify(secret, rawBody, header, System.currentTimeMillis() / 1000);
    }

    public static boolean verify(String secret, byte[] rawBody, String header, long nowSeconds) {
        if (header == null || header.isEmpty()) return false;
        Map<String, String> parts = new HashMap<>();
        for (String part : header.split(",")) {
            String[] kv = part.trim().split("=", 2);
            if (kv.length == 2) parts.put(kv[0], kv[1]);
        }
        String t = parts.getOrDefault("t", "");
        String v1 = parts.getOrDefault("v1", "");
        if (!t.matches("[0-9]{1,18}") || v1.isEmpty()) return false;
        if (Math.abs(nowSeconds - Long.parseLong(t)) > TOLERANCE_SECONDS) return false;
        try {
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
            mac.update((t + ".").getBytes(StandardCharsets.UTF_8));
            byte[] expected = HexFormat.of().formatHex(mac.doFinal(rawBody)).getBytes(StandardCharsets.UTF_8);
            return MessageDigest.isEqual(expected, v1.getBytes(StandardCharsets.UTF_8));
        } catch (GeneralSecurityException e) {
            throw new IllegalStateException(e);
        }
    }
}
Go: signature.go
package webhooks

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

const toleranceSeconds = 300

// VerifyStraitSignature reports whether header is a valid X-Strait-Signature for body.
func VerifyStraitSignature(secret string, body []byte, header string, now time.Time) bool {
	var t, v1 string
	for _, part := range strings.Split(header, ",") {
		k, v, _ := strings.Cut(strings.TrimSpace(part), "=")
		switch k {
		case "t":
			t = v
		case "v1":
			v1 = v
		}
	}
	ts, err := strconv.ParseInt(t, 10, 64)
	if err != nil || ts <= 0 || v1 == "" {
		return false
	}
	if d := now.Unix() - ts; d > toleranceSeconds || d < -toleranceSeconds {
		return false
	}
	mac := hmac.New(sha256.New, []byte(secret))
	mac.Write([]byte(t + "."))
	mac.Write(body)
	expected := hex.EncodeToString(mac.Sum(nil))
	return hmac.Equal([]byte(expected), []byte(v1))
}

You should see: your function return true for the vector in step 2 when you pass "now" as 1800000000, and false when you pass 1800000301 or change one character of the body.

4. Call it with the raw body in your framework

The one mistake that breaks every verifier is hashing parsed-and-reserialised JSON instead of the bytes we sent. Each framework below hands you the raw body:

Node: Express
import express from 'express';
import { verifyStraitSignature } from './strait-signature.mjs';

const app = express();

app.post('/webhooks/strait', express.raw({ type: 'application/json' }), (req, res) => {
  if (!verifyStraitSignature(process.env.WEBHOOK_SECRET, req.body, req.get('X-Strait-Signature'))) {
    return res.status(401).end();
  }
  const event = JSON.parse(req.body.toString('utf8'));
  console.log(event.event, event.data);
  res.status(204).end();
});
PHP: Laravel route
<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

// routes/api.php (no CSRF check there). Load verify_strait_signature() via Composer "files" autoload.
Route::post('/webhooks/strait', function (Request $request) {
    $ok = verify_strait_signature(
        (string) config('services.strait.webhook_secret'),
        $request->getContent(), // the raw body
        $request->header('X-Strait-Signature'),
    );
    abort_unless($ok, 401);
    $event = json_decode($request->getContent(), true);
    logger()->info('strait webhook', ['event' => $event['event']]);
    return response()->noContent();
});
Python: Flask
import os

from flask import Flask, abort, request

from strait_signature import verify_strait_signature

app = Flask(__name__)


@app.post("/webhooks/strait")
def strait_webhook():
    raw = request.get_data()  # the exact bytes we sent
    if not verify_strait_signature(os.environ["WEBHOOK_SECRET"], raw, request.headers.get("X-Strait-Signature")):
        abort(401)
    event = request.get_json()
    print(event["event"], event["data"])
    return "", 204
Java: Spring Boot
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class StraitWebhookController {
    private final String secret = System.getenv("WEBHOOK_SECRET");

    // byte[] gets the raw body; a String or an object would not match the signature.
    @PostMapping("/webhooks/strait")
    public ResponseEntity<Void> receive(@RequestBody byte[] body,
                                        @RequestHeader(value = "X-Strait-Signature", required = false) String signature) {
        if (!StraitSignature.verify(secret, body, signature)) {
            return ResponseEntity.status(401).build();
        }
        // parse body with your JSON library, then handle event / data
        return ResponseEntity.noContent().build();
    }
}
Go: net/http handler
package webhooks

import (
	"io"
	"net/http"
	"os"
	"time"
)

func Handler(w http.ResponseWriter, r *http.Request) {
	body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
	if err != nil || !VerifyStraitSignature(os.Getenv("WEBHOOK_SECRET"), body, r.Header.Get("X-Strait-Signature"), time.Now()) {
		http.Error(w, "invalid signature", http.StatusUnauthorized)
		return
	}
	// json.Unmarshal(body, &event); handle event.Event / event.Data
	w.WriteHeader(http.StatusNoContent)
}

For Django, use request.body. For FastAPI, await request.body(). Reply within 5 seconds, then do slow work in a queue.

You should see: a request to your endpoint with a made-up header, such as curl -X POST https://your-server/webhooks/strait -H "X-Strait-Signature: t=1,v1=00" -d '{}', gets 401.

5. Send a test event

Press Send test event next to the webhook in the dashboard, or call Test a webhook from your server:

Terminal
curl -X POST https://strait.link/v1/webhooks/<webhook id>/test \
  -H "Authorization: Bearer $SECRET_KEY"

You should see: "delivered": true and "status": 204 in the answer, and your handler logging a ping event.

6. Ignore repeats

Delivery is at least once: a retry carries the same X-Strait-Delivery id (also id in the body) and a new signature. Store the ids you've handled, for example in a table with a unique key or Redis with SET NX and a 7-day expiry, and return 2xx for a repeat without doing the work again.

You should see: when you send your endpoint the same logged body and headers twice within 5 minutes, the event is handled once and both requests get 2xx.

Common errors

  • Every signature fails, even the test event. The body was parsed before you hashed it (express.json(), Spring with a String or object, Laravel $request->all()). Hash the raw bytes, as in step 4. Also check the secret has no stray quotes or newline from your .env file.
  • Signatures pass locally but fail in production. The server clock is off by more than 5 minutes. Turn on NTP time sync.
  • A proxy or gateway rejects or rewrites the request. Some API gateways re-encode JSON or strip unknown headers. Pass X-Strait-Signature through and leave the body untouched.

Next steps