Search code examples
symfonysymfony4

Symfony : EventSubscriber. trigger a 404 page when a route require user must be authenticated (depending of the .env var)


In my project, I create some controllers and some routes.

I added to some controller and some specific route this condition "@IsGranted("IS_AUTHENTICATED_FULLY")" like this :

enter image description here

Depending of the env variable, I want to disable routes who need to be authentificated (disable = redirect automatically to a 404 page). My question :

From a EventSubscriber, how can I check if the current route need an anthentificated user ?


Solution

  • You can use the kernel.exception event to get notified of a 403 / Forbidden exception that Symfony will automatically throw in this situation. In the event handler you can override the response and replace it with a RedirectResponse:

    <?php
    
    namespace App;
    
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    use Symfony\Component\HttpKernel\Event\ExceptionEvent;
    use Symfony\Component\HttpKernel\KernelEvents;
    
    class ControllerListener implements EventSubscriberInterface
    {
        public static function getSubscribedEvents()
        {
            return [
                KernelEvents::EXCEPTION => 'onException',
            ];
        }
    
        public function onException(ExceptionEvent $event)
        {
            // implement custom logic and set your response, eg.:
            // $event->setResponse(new RedirectResponse(...))
        }
    }
    

    Another way is to override the framework.error_controller configuration and implementing a custom controller. Within the configured controller action you can the also return a RedirectResponse.

    # config/packages/framework.yaml
    framework:
        error_controller: App\Controller\ErrorController::show