In some applications are required to block access to the website for certain users by IP address. In this case, IP blacklisting can be used to filter out malicious IP addresses that want to access a website.
This tutorial shows example how to block access by IP address in Laravel 9 application.
Add new environment variable IP_BLACKLIST
in the .env
file. Variable is a comma separated list of banned IP addresses.
IP_BLACKLIST=192.168.0.4,192.168.0.10
In the config/auth.php
file add ip_blacklist
option.
<?php
return [
// Other options ...
'ip_blacklist' => explode(',', env('IP_BLACKLIST', '')),
// Other options ...
];
Clear configuration cache using command:
php artisan config:cache
Create middleware and check if the client IP address is in the blacklist. If it is, throw AccessDeniedHttpException
exception.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
class RestrictIpAddressMiddleware
{
public function handle(Request $request, Closure $next): mixed
{
if (in_array($request->getClientIp(), config('auth.ip_blacklist'), true)) {
throw new AccessDeniedHttpException('Access Denied');
}
return $next($request);
}
}
Define the middleware in the middlewareGroups
array which is in the Kernel.php
file.
<?php
namespace App\Http;
use App\Http\Middleware\RestrictIpAddressMiddleware;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
// ...
protected $middlewareGroups = [
'web' => [
// ...
RestrictIpAddressMiddleware::class,
],
// ...
];
// ...
}
Leave a Comment
Cancel reply