Block Access by IP Address in Symfony 7

Block Access by IP Address in Symfony 7

In some applications might need to block access to the website for certain users by IP address. In such case, IP blacklisting can be used to filter out malicious IP addresses to accessing website.

This tutorial provides example how to block access by IP address in Symfony 7 application.

In the .env file, add a new environment variable IP_BLACKLIST which holds the banned IP addresses separated comma.

.env

IP_BLACKLIST=192.168.0.4,192.168.0.10

Create the event subscriber which listens kernel.request event. It can be useful to early stopping request handling. Check if the client IP address is in the blacklist, if it is, throw AccessDeniedHttpException exception.

src/EventSubscriber/RestrictIpAddressSubscriber.php

<?php

namespace App\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

class RestrictIpAddressSubscriber implements EventSubscriberInterface
{
    public function __construct(private array $ipBlacklist)
    {
    }

    public static function getSubscribedEvents(): array
    {
        return [RequestEvent::class => 'onKernelRequest'];
    }

    public function onKernelRequest(RequestEvent $event): void
    {
        if (!$event->isMainRequest()) {
            return;
        }

        if (in_array($event->getRequest()->getClientIp(), $this->ipBlacklist, true)) {
            throw new AccessDeniedHttpException('Access Denied');
        }
    }
}

In the services.yaml file, pass the IP blacklist as argument to constructor of the event subscriber.

config/services.yaml

services:
    # ...
    
    App\EventSubscriber\RestrictIpAddressSubscriber:
        arguments: ['%env(csv:IP_BLACKLIST)%']

Leave a Comment

Cancel reply

Your email address will not be published.