src/Security/AccessDeniedListener.php line 23

Open in your IDE?
  1. <?php
  2. // src/EventListener/AccessDeniedListener.php
  3. namespace App\Security;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  9. class AccessDeniedListener implements EventSubscriberInterface
  10. {
  11.     public static function getSubscribedEvents(): array
  12.     {
  13.         return [
  14.             // the priority must be greater than the Security HTTP
  15.             // ExceptionListener, to make sure it's called before
  16.             // the default exception listener
  17.             KernelEvents::EXCEPTION => ['onKernelException'2],
  18.         ];
  19.     }
  20.     public function onKernelException(ExceptionEvent $event): void
  21.     {
  22.         $exception $event->getThrowable();
  23.         if (!$exception instanceof AccessDeniedException) {
  24.             return;
  25.         }
  26.         // ... perform some action (e.g. logging)
  27.         // optionally set the custom response
  28.         $event->setResponse(new Response(null403));
  29.         // or stop propagation (prevents the next exception listeners from being called)
  30.         //$event->stopPropagation();
  31.     }
  32. }
  33. ?>