Skip to content

Instantly share code, notes, and snippets.

@shawnlindstrom
Created October 25, 2024 19:23
Show Gist options
  • Save shawnlindstrom/6f969813c2ca1839a41fd797b04ad24c to your computer and use it in GitHub Desktop.
Save shawnlindstrom/6f969813c2ca1839a41fd797b04ad24c to your computer and use it in GitHub Desktop.
Laravel Middleware to Validate Twilio Webhook IP
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class ValidateTwilioEventWebhook
{
public function handle(Request $request, Closure $next): Response
{
if (! $this->ipWithinRange($request->ip(), config('twilio.webhook_cidr'))) {
return response('Forbidden', 403);
}
return $next($request);
}
private function ipWithinRange($ip, $cidr): bool
{
[$subnet, $mask] = explode('/', $cidr);
$ip = inet_pton($ip);
$subnet = inet_pton($subnet);
$bitmask = str_repeat("\xFF", $mask >> 3);
$bitmask .= chr((0xFF << (8 - ($mask & 7))) & 0xFF);
$bitmask = str_pad($bitmask, 16, "\0");
return ($ip & $bitmask) === ($subnet & $bitmask);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment