src/EventListener/AccessDeniedListener.php line 33

  1. <?php
  2. // src/EventListener/AccessDeniedListener.php
  3. namespace App\EventListener;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpFoundation\RedirectResponse;
  6. use Symfony\Component\HttpFoundation\Response;
  7. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  8. use Symfony\Component\HttpKernel\KernelEvents;
  9. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  10. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  11. use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;
  12. class AccessDeniedListener implements EventSubscriberInterface
  13. {
  14.     private $urlGenerator;
  15.     public function __construct(UrlGeneratorInterface $urlGenerator)
  16.     {
  17.         $this->urlGenerator $urlGenerator;
  18.     }
  19.     public static function getSubscribedEvents(): array
  20.     {
  21.         return [
  22.             // the priority must be greater than the Security HTTP
  23.             // ExceptionListener, to make sure it's called before
  24.             // the default exception listener
  25.             KernelEvents::EXCEPTION => ['onKernelException'2],
  26.         ];
  27.     }
  28.     public function onKernelException(ExceptionEvent $event): void
  29.     {
  30.         $exception $event->getThrowable();
  31.         if (!$exception instanceof AccessDeniedException) {
  32.             return;
  33.         }
  34.         // ... perform some action (e.g. logging)
  35.         // optionally set the custom response
  36.         //Fixme -- flash message is not working but redirect is fine.
  37.         $flashMessage = new FlashBag();
  38.         $flashMessage->set('notice'"You don't have permission to access this page." );
  39.         $response = new RedirectResponse($this->urlGenerator->generate('app_home'));
  40.         $event->setResponse($response);
  41.         //$event->setResponse(new Response(null, 403));
  42.         // or stop propagation (prevents the next exception listeners from being called)
  43.         //$event->stopPropagation();
  44.     }
  45. }