Webhook HMAC-SHA256 Verifier · GitHub + Laravel

GitHub Webhook X-Hub-Signature-256 Verification in Laravel (Queues & Raw Body)

Verify and generate GitHub + Laravel HMAC-SHA256 signatures locally using crypto.subtle. Compare raw-body vs re-serialized JSON hashes side by side and copy constant-time verification code below.

Written & verified by Chathura Prabashana · Updated November 2026

1. Adjust payload/secret or load a test scenario2. Inspect live HMAC & diagnostics3. Copy handler code
Quick-Test Scenarios:

1. Provider, Secret & Header

Whitespace and line endings affect the HMAC digest. Edit the raw payload below to test byte-level changes.

Test Signature Generated·X-Hub-Signature-256

X-Hub-Signature-256: sha256=7506eb40e92eb5aa0cc177df55da253bda9042cd7a023c7fcaa17b4a67e6a6c0

<?php
// app/Http/Controllers/GitHubWebhookController.php (Laravel 11/12)
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;

class GitHubWebhookController extends Controller
{
    public function __invoke(Request $request): Response
    {
        $rawBody = $request->getContent(); // NEVER use json_encode($request->all())
        $header = (string) $request->header('X-Hub-Signature-256', '');
        $secret = (string) config('services.github.webhook_secret');

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

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

        return response('OK', 200);
    }
}
1. Raw Body HMAC (HEX)Valid

7506eb40e92eb5aa0cc177df55da253bda9042cd7a023c7fcaa17b4a67e6a6c0

Untouched raw request bytes (indentation and newlines preserved).

2. Re-Serialized JSON HMACMismatch

b56ce5a962511720856d6e2f54af006a683ba4bb04671f914d5bbc3f7d520645

Digest produced if JSON middleware parses and re-encodes the body.

HMAC & Raw-Body Diagnostics

  • criticalRaw Body vs. Re-Serialized JSON Produces Two Different Signatures

    Notice in the comparison box below: hashing this exact raw payload produces a completely different HMAC than hashing JSON.stringify(JSON.parse(payload)). Never run express.json(), request.json(), or json_encode($request->all()) before verifying webhook signatures.

  • infoAlways Use Constant-Time Comparison (Never === or ==)

    Compare computed and received digests with hash_equals() (PHP/Laravel), hmac.compare_digest() (Python/FastAPI), crypto.timingSafeEqual() (Node.js/Next.js/Express), or CryptographicOperations.FixedTimeEquals() (ASP.NET Core) to prevent timing side-channel attacks.

Runs locally in your browser using window.crypto.subtle. Webhook secrets and payloads are never sent to a server.

Typical Webhook Signature Verification Error (GitHub + Laravel)

When middleware consumes the raw HTTP stream, JSON gets re-serialized before hashing, or encoding/prefixes mismatch in GitHub + Laravel, your server logs an exception matching the output below:

Server Exception / Webhook Delivery Log

HTTP 401 Unauthorized: Invalid GitHub webhook signature — hash_equals failed because json_encode($request->all()) altered escaped slashes in GitHub URLs.

Raw Request Stream Handling & Replay Protection in GitHub + Laravel

Verifying GitHub webhooks in Laravel 11 and 12; whether triggering automated deployments, syncing GitHub Issues into an internal CRM, or auditing repository pushes; is clean and zero-dependency when built on PHP's built-in hash_hmac() and hash_equals() functions. Yet PHP's json_encode() introduces a classic trap: PHP escapes forward slashes ("https://github.com" becomes "https:\/\/github.com") by default.

Because every GitHub webhook payload contains dozens of repository and avatar URLs with forward slashes, running json_encode($request->all()) produces a completely different byte sequence from the raw JSON GitHub signed. Calling $request->getContent() reads the exact untouched HTTP request stream so hash_hmac("sha256", $rawBody, $secret) matches GitHub's X-Hub-Signature-256 header identically.

To protect your webhook endpoint cleanly across multiple routes, wrap verification inside a dedicated Laravel route middleware (VerifyGitHubWebhook) applied to routes/api.php (which bypasses session/CSRF middleware automatically). Always compare "sha256=" . hash_hmac(..) using hash_equals() so timing attacks cannot forge valid digests.

Because GitHub marks deliveries failed if your server takes longer than 10 seconds to reply, verify the signature, deduplicate via Cache::add("gh_delivery:{$deliveryId}", true, now()->addDay()), dispatch a queued Laravel Job onto Redis/MySQL, and immediately return HTTP 202 Accepted.

Use the interactive Web Crypto debugger above to generate valid X-Hub-Signature-256 headers for any push or pull_request payload and verify how PHP raw-body hashing avoids JSON re-serialization failures.

For production Laravel applications ingesting GitHub push, release, or pull_request webhooks behind Nginx, placing VerifyGitHubWebhook middleware on routes/api.php ensures every request is authenticated against raw stream bytes before touching Eloquent or Redis queues. Always monitor failed_jobs in Laravel Horizon so transient downstream API failures can be retried cleanly without asking GitHub to redeliver historical events.

Step-by-Step GitHub + Laravel Webhook Verification Setup

Follow each step below to preserve untouched raw request bytes, enforce constant-time HMAC verification, and offload webhook jobs asynchronously for fast 2xx acknowledgments.

  1. 1Create a Reusable Laravel Middleware for X-Hub-Signature-256

    app/Http/Middleware/VerifyGitHubWebhook.php

    Verify the raw body stream via $request->getContent() and PHP's constant-time hash_equals() before the request ever reaches your controller.

    app/Http/Middleware/VerifyGitHubWebhook.phpphp
    <?php
    
    namespace App\Http\Middleware;
    
    use Closure;
    use Illuminate\Http\Request;
    use Symfony\Component\HttpFoundation\Response;
    
    class VerifyGitHubWebhook
    {
        public function handle(Request $request, Closure $next): Response
        {
            $signature = (string) $request->header('X-Hub-Signature-256', '');
            $secret = (string) config('services.github.webhook_secret');
    
            if ($signature === '' || $secret === '') {
                abort(401, 'Missing GitHub webhook signature or secret');
            }
    
            $expected = 'sha256=' . hash_hmac('sha256', $request->getContent(), $secret);
    
            if (! hash_equals($expected, $signature)) {
                abort(401, 'Invalid GitHub webhook signature');
            }
    
            return $next($request);
        }
    }
  2. 2Dispatch an Idempotent Queued Job for Fast 202 Responses

    app/Http/Controllers/GitHubWebhookController.php

    Use Cache::add() on the X-GitHub-Delivery UUID to ignore retries safely and offload work to your Laravel queue worker.

    app/Http/Controllers/GitHubWebhookController.phpphp
    <?php
    
    namespace App\Http\Controllers;
    
    use App\Jobs\HandleGitHubWebhook;
    use Illuminate\Http\JsonResponse;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Cache;
    
    class GitHubWebhookController extends Controller
    {
        public function __invoke(Request $request): JsonResponse
        {
            $deliveryId = (string) $request->header('X-GitHub-Delivery', '');
            $event = (string) $request->header('X-GitHub-Event', 'unknown');
    
            if ($deliveryId !== '' && ! Cache::add("gh_delivery:{$deliveryId}", true, now()->addDay())) {
                return response()->json(['status' => 'duplicate_ignored'], 200);
            }
    
            HandleGitHubWebhook::dispatch($event, $request->json()->all());
    
            return response()->json(['status' => 'queued', 'event' => $event], 202);
        }
    }
  3. 3Register the Webhook Route Inside routes/api.php

    routes/api.php

    Mounting inside routes/api.php avoids CSRF token checks automatically while attaching your signature middleware.

    routes/api.phpphp
    use App\Http\Controllers\GitHubWebhookController;
    use App\Http\Middleware\VerifyGitHubWebhook;
    use Illuminate\Support\Facades\Route;
    
    Route::post('/webhooks/github', GitHubWebhookController::class)
        ->middleware(VerifyGitHubWebhook::class);
  4. 4Test Locally With curl Using a Signature Generated Above

    terminal

    Send a raw payload with X-Hub-Signature-256 and confirm HTTP 202 Accepted without any CSRF or signature mismatch.

    terminalbash
    curl -i -X POST http://127.0.0.1:8000/api/webhooks/github \
      -H "Content-Type: application/json" \
      -H "X-GitHub-Event: push" \
      -H "X-GitHub-Delivery: demo-uuid-001" \
      -H "X-Hub-Signature-256: sha256=<paste_expected_hex_from_tool>" \
      --data-binary @payload.json

Common GitHub + Laravel Webhook Pitfalls

Avoid these three subtle production failure modes when verifying external webhook signatures.

Pitfall 1

Using json_encode($request->all()) Corrupting Forward Slashes in URLs

PHP's json_encode() escapes "/" into "\/" by default. Every GitHub webhook payload includes dozens of "https://api.github.com/.." URLs, guaranteeing immediate HMAC failure if you re-encode.

Pitfall 2

Calling env("GITHUB_WEBHOOK_SECRET") Directly Inside Middleware

After php artisan config:cache runs in production, env() returns null outside config/*.php; causing your middleware to reject every valid GitHub delivery with 401. Always read via config("services.github.webhook_secret").

Pitfall 3

Using --data Instead of --data-binary When Testing With curl

curl's -d / --data flag strips newline characters from multi-line JSON files before sending, breaking HMAC signatures computed over formatted JSON. Always use --data-binary when testing webhooks via curl.

Related Tools

Audit Your Webhook Signing Secrets & Nginx Reverse Proxy Headers

Make sure your .env signing secret has no trailing spaces or unquoted # truncation and your Nginx proxy forwards raw POST payloads without 301 redirects:

Frequently Asked Questions

Does Laravel $request->getContent() work multiple times on the same request?
Yes. Symfony/Laravel caches the raw request body string internally on the Request object after the first getContent() call, so reading it in VerifyGitHubWebhook middleware and parsing $request->json()->all() in the controller works cleanly.
Why did GitHub return 419 Page Expired to my Laravel webhook?
Your webhook route was registered in routes/web.php where Laravel's ValidateCsrfToken middleware runs. Move it to routes/api.php or add it to validateCsrfTokens(except: [..]) in bootstrap/app.php.
Should I verify GitHub IP ranges in Nginx in addition to HMAC?
HMAC-SHA256 verification with a strong 32-byte secret is cryptographically stronger and does not break when GitHub rotates IP ranges. HMAC alone is sufficient and recommended by GitHub.
What happens if my Laravel queue worker is temporarily stopped when a webhook arrives?
Because the controller writes the job cleanly to Redis or MySQL and returns 202 Accepted, GitHub considers delivery successful and your worker processes the queued events automatically as soon as it restarts.
Browse all 10 webhook guides →