Created
October 25, 2024 19:23
-
-
Save shawnlindstrom/6f969813c2ca1839a41fd797b04ad24c to your computer and use it in GitHub Desktop.
Laravel Middleware to Validate Twilio Webhook IP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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