← Back to All Articles

Securing Laravel REST APIs & Webhooks: HMAC Signatures and Rate Limiting

By Gulfaraz Arshad • Published November 17, 2026 • 6 min read
Laravel Security REST API Webhooks Redis

Why Public Webhook Endpoints Need Cryptographic Verification

Webhook endpoints receiving delivery receipts, inbound SMS opt-outs, or payment callbacks are exposed to the public internet without user session cookies. Relying on "security through obscurity" with a hard-to-guess URL path is fragile—anyone who intercepts or guesses the endpoint can spoof payloads, mark invoices as paid, or trigger unauthorized downstream jobs.

To lock down incoming webhook routes in Laravel, combine HMAC-SHA256 signature verification, timestamp replay windows, and constant-time string comparison inside dedicated route middleware.

1. Building an HMAC Signature Middleware

Always hash the raw request body ($request->getContent()) combined with a timestamp header, and compare digests using hash_equals() rather than === to prevent timing side-channel attacks:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class VerifyWebhookSignature
{
    public function handle(Request $request, Closure $next): Response
    {
        $signature = $request->header('X-Webhook-Signature');
        $timestamp = $request->header('X-Webhook-Timestamp');

        if (! $signature || ! $timestamp || ! ctype_digit((string) $timestamp)) {
            abort(401, 'Missing webhook authentication headers.');
        }

        // Reject requests older than 5 minutes to prevent replay attacks
        if (abs(time() - (int) $timestamp) > 300) {
            abort(401, 'Webhook timestamp expired.');
        }

        $signedPayload = $timestamp . '.' . $request->getContent();
        $expected = hash_hmac('sha256', $signedPayload, config('services.webhook.secret'));

        if (! hash_equals($expected, $signature)) {
            abort(401, 'Invalid webhook signature.');
        }

        return $next($request);
    }
}

2. Enforcing Idempotency on Webhook Retries

Upstream providers retry webhook deliveries whenever your server takes too long to respond or returns a 5xx status. Using Redis atomic locks (Cache::add()) guarantees that duplicate event IDs are acknowledged immediately without executing side effects twice:

$eventId = $request->input('event_id');

// Atomically claim this event ID for 24 hours
if (! Cache::add("webhook:processed:{$eventId}", true, now()->addDay())) {
    return response()->json(['status' => 'already_processed'], 200);
}

ProcessInboundEventJob::dispatch($request->validated());

return response()->json(['status' => 'accepted'], 202);

3. Layered Rate Limiting by API Key and IP

In AppServiceProvider::boot(), define tiered RateLimiter policies so a burst from one tenant never degrades latency for other clients:

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;

RateLimiter::for('tenant-api', function (Request $request) {
    $tenantKey = $request->user()?->id ?: $request->ip();

    return [
        Limit::perMinute(300)->by("tenant:{$tenantKey}"),
        Limit::perSecond(15)->by("burst:{$tenantKey}"),
    ];
});

Always configure your web server (Nginx or Cloudflare) to pass trusted proxy headers accurately so $request->ip() resolves the true client IP address rather than your load balancer's internal IP.

Gulfaraz Arshad

Written by Gulfaraz Arshad

Software Developer at Cruise Brains specializing in Laravel, PHP, MySQL performance optimization, and high-throughput API architectures.