ENGINEERING JOURNAL

Verifying Webhook Signatures with HMAC in Laravel

Learn how to verify webhook signatures with HMAC in Laravel: sign the raw body, compare with hash_equals, and reject forged requests with a 401.

THE ARTICLE 01 — 02

Any public URL that accepts POST requests will eventually receive traffic you did not ask for. A webhook endpoint is worse than most, because it triggers real work: creating records, sending emails, charging a customer, retrying a delivery. If you process a webhook without checking who sent it, anyone who finds the URL can fire fake events at your app. Verifying the webhook signature with HMAC is the standard fix, and it takes less code than most developers expect.

The idea is simple. You and the sender share a secret. The sender signs the request body with that secret using HMAC-SHA256 and puts the signature in a header. Your endpoint recomputes the signature from the raw body and the same secret. If the two match, the request came from someone who knows the secret. If they do not match, you reject it with a 401 and move on.

Use the raw body, not the parsed JSON

This is the mistake that breaks most first implementations. The signature is computed over the exact bytes the sender transmitted. If you decode the JSON into an array and re-encode it, the bytes change: key order, whitespace, and escaping can all differ, and your computed signature will never match. In Laravel, always read the raw body with $request->getContent() and sign that string directly. Never sign $request->all() or json_encode($request->all()).

Store the secret in the environment, not in code

Put the webhook secret in .env and read it through config, the same way you handle any credential. A secret committed to Git is a secret you have already leaked, and rotating it after a leak means coordinating with every sender that uses it.

# .env
WEBHOOK_SECRET=your-shared-secret-here

# config/services.php
'webhooks' => [
    'secret' => env('WEBHOOK_SECRET'),
],

Verify the signature in middleware

Verification belongs in middleware, before the request reaches a controller. That way no unverified payload ever touches your business logic, and every webhook route gets the same check. Here is a middleware that handles the common signed-payload format: a timestamp header plus an HMAC signature header.

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class VerifyWebhookSignature
{
    public function handle(Request $request, Closure $next)
    {
        $secret = config('services.webhooks.secret');
        $signature = $request->header('X-Signature');
        $timestamp = (int) $request->header('X-Timestamp');

        if (! $signature || ! $timestamp) {
            return response('Missing signature', 401);
        }

        // Reject replays: ignore requests older than five minutes.
        if (abs(time() - $timestamp) > 300) {
            return response('Stale webhook', 401);
        }

        $payload = $timestamp . '.' . $request->getContent();
        $expected = hash_hmac('sha256', $payload, $secret);

        if (! hash_equals($expected, $signature)) {
            return response('Invalid signature', 401);
        }

        return $next($request);
    }
}

Two details matter here. First, hash_equals compares the strings in constant time, so an attacker cannot learn the signature one character at a time by measuring response times. Second, the timestamp check stops replay attacks: even if someone captures a valid signed request, they can only reuse it for five minutes, and your idempotency handling should catch the duplicate anyway.

Different providers sign differently

Not every sender uses the timestamp dot payload format above. Stripe sends a header like t=1492774577,v1=abc123 and signs timestamp.payload. GitHub sends X-Hub-Signature-256 with a sha256= prefix and signs the raw body alone. Svix sends svix-id, svix-timestamp, and svix-signature and signs id.timestamp.body. The principle is always the same, but the exact string that gets signed and the header names change. Read the provider's docs, copy their format exactly, and write a test that signs a payload the way the provider does and asserts your endpoint accepts it.

Log rejections, but never log the secret

When verification fails, log the event: the route, the timestamp header, the sender IP, and whether the signature was missing, stale, or mismatched. That log is how you debug a broken integration later, and it is also how you spot someone probing your endpoint. Never log the secret itself, and never log the expected signature. A log line that contains enough information to forge a request is worse than no log at all. Keep the rejection response short and generic: a 401 with no explanation of which check failed.

Test the unhappy paths, not just the happy one

Write tests for the cases that actually break in production: a valid signature that passes, a tampered body that fails, a missing signature header, a timestamp ten minutes old, and a signature computed over re-encoded JSON instead of the raw body. The last one is the most common real-world bug, and a test catches it before a provider's first live event bounces off your endpoint.

Signature verification does not replace the rest of webhook hygiene. Once a payload is verified, you still want idempotent processing so a retried delivery does not repeat a side effect. I wrote about that separately in Webhook Delivery Retries: Exponential Backoff Done Right. Verification answers "did the real sender send this?" Idempotency answers "have I already processed this?" You need both before a webhook endpoint is safe to expose.

The takeaway is short. Read the raw body, sign it with HMAC-SHA256 and a secret from the environment, compare with hash_equals, enforce a timestamp window, and reject everything else with a 401. That is the whole mechanism, and it is the difference between a webhook endpoint and an open door.

Muhammad Aqib ← ALL ARTICLES
KEEP EXPLORING

More ideas.
Better engineering.

Explore the journal ↗