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:
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.
1Create a Reusable Laravel Middleware for X-Hub-Signature-256
app/Http/Middleware/VerifyGitHubWebhook.phpVerify 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); } }2Dispatch an Idempotent Queued Job for Fast 202 Responses
app/Http/Controllers/GitHubWebhookController.phpUse 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); } }3Register the Webhook Route Inside routes/api.php
routes/api.phpMounting inside routes/api.php avoids CSRF token checks automatically while attaching your signature middleware.
routes/api.phpphpuse App\Http\Controllers\GitHubWebhookController; use App\Http\Middleware\VerifyGitHubWebhook; use Illuminate\Support\Facades\Route; Route::post('/webhooks/github', GitHubWebhookController::class) ->middleware(VerifyGitHubWebhook::class);4Test Locally With curl Using a Signature Generated Above
terminalSend a raw payload with X-Hub-Signature-256 and confirm HTTP 202 Accepted without any CSRF or signature mismatch.
terminalbashcurl -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.
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.
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").
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.
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:
Validate CI/CD and GitHub Actions .env files locally in your browser. Fix POSIX source .env syntax errors, unquoted spaces, and accidental secret exposure.
Configure Nginx reverse proxy for Laravel Octane (FrankenPHP/Swoole) on port 8000 and Laravel Reverb WebSockets on port 8080 with SSL and 3600s timeouts.
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.
Related Webhook HMAC Verification Guides
Browse all 10 webhook guides →Stripe Webhook Signature Verification in Laravel (Raw Body & CSRF Fix)
Fix Stripe SignatureVerificationException in Laravel 11/12 using $request->getContent(), CSRF exclusion in bootstrap/app.php, hash_equals, and async queues.
GitHub Webhook X-Hub-Signature-256 Verification in Node.js Express
Verify GitHub X-Hub-Signature-256 HMAC-SHA256 webhooks in Express.js using raw Buffers, sha256= prefix validation, and crypto.timingSafeEqual.
Shopify Base64 HMAC Webhook Verification in Laravel (Binary hash_hmac Fix)
Verify Shopify X-Shopify-Hmac-Sha256 webhooks in Laravel 11/12 using base64_encode with binary hash_hmac, $request->getContent(), and hash_equals.
ASP.NET Core 8/9 Raw Body Webhook HMAC Verification (EnableBuffering Guide)
Verify Stripe, GitHub, and Shopify HMAC-SHA256 webhooks in ASP.NET Core 8/9 using EnableBuffering(), StreamReader, and FixedTimeEquals in C#.