vendor/symfony/security-http/Firewall/ExceptionListener.php line 88

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Symfony\Component\Security\Http\Firewall;
  11. use Psr\Log\LoggerInterface;
  12. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpFoundation\Response;
  15. use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
  16. use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
  17. use Symfony\Component\HttpKernel\Exception\HttpException;
  18. use Symfony\Component\HttpKernel\HttpKernelInterface;
  19. use Symfony\Component\HttpKernel\KernelEvents;
  20. use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface;
  21. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  22. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  23. use Symfony\Component\Security\Core\Exception\AccountStatusException;
  24. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  25. use Symfony\Component\Security\Core\Exception\InsufficientAuthenticationException;
  26. use Symfony\Component\Security\Core\Exception\LogoutException;
  27. use Symfony\Component\Security\Core\Security;
  28. use Symfony\Component\Security\Http\Authorization\AccessDeniedHandlerInterface;
  29. use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;
  30. use Symfony\Component\Security\Http\HttpUtils;
  31. use Symfony\Component\Security\Http\Util\TargetPathTrait;
  32. /**
  33.  * ExceptionListener catches authentication exception and converts them to
  34.  * Response instances.
  35.  *
  36.  * @author Fabien Potencier <fabien@symfony.com>
  37.  */
  38. class ExceptionListener
  39. {
  40.     use TargetPathTrait;
  41.     private $tokenStorage;
  42.     private $providerKey;
  43.     private $accessDeniedHandler;
  44.     private $authenticationEntryPoint;
  45.     private $authenticationTrustResolver;
  46.     private $errorPage;
  47.     private $logger;
  48.     private $httpUtils;
  49.     private $stateless;
  50.     public function __construct(TokenStorageInterface $tokenStorageAuthenticationTrustResolverInterface $trustResolverHttpUtils $httpUtilsstring $providerKeyAuthenticationEntryPointInterface $authenticationEntryPoint nullstring $errorPage nullAccessDeniedHandlerInterface $accessDeniedHandler nullLoggerInterface $logger nullbool $stateless false)
  51.     {
  52.         $this->tokenStorage $tokenStorage;
  53.         $this->accessDeniedHandler $accessDeniedHandler;
  54.         $this->httpUtils $httpUtils;
  55.         $this->providerKey $providerKey;
  56.         $this->authenticationEntryPoint $authenticationEntryPoint;
  57.         $this->authenticationTrustResolver $trustResolver;
  58.         $this->errorPage $errorPage;
  59.         $this->logger $logger;
  60.         $this->stateless $stateless;
  61.     }
  62.     /**
  63.      * Registers a onKernelException listener to take care of security exceptions.
  64.      */
  65.     public function register(EventDispatcherInterface $dispatcher)
  66.     {
  67.         $dispatcher->addListener(KernelEvents::EXCEPTION, [$this'onKernelException'], 1);
  68.     }
  69.     /**
  70.      * Unregisters the dispatcher.
  71.      */
  72.     public function unregister(EventDispatcherInterface $dispatcher)
  73.     {
  74.         $dispatcher->removeListener(KernelEvents::EXCEPTION, [$this'onKernelException']);
  75.     }
  76.     /**
  77.      * Handles security related exceptions.
  78.      */
  79.     public function onKernelException(GetResponseForExceptionEvent $event)
  80.     {
  81.         $exception $event->getException();
  82.         do {
  83.             if ($exception instanceof AuthenticationException) {
  84.                 return $this->handleAuthenticationException($event$exception);
  85.             } elseif ($exception instanceof AccessDeniedException) {
  86.                 return $this->handleAccessDeniedException($event$exception);
  87.             } elseif ($exception instanceof LogoutException) {
  88.                 return $this->handleLogoutException($exception);
  89.             }
  90.         } while (null !== $exception $exception->getPrevious());
  91.     }
  92.     private function handleAuthenticationException(GetResponseForExceptionEvent $eventAuthenticationException $exception): void
  93.     {
  94.         if (null !== $this->logger) {
  95.             $this->logger->info('An AuthenticationException was thrown; redirecting to authentication entry point.', ['exception' => $exception]);
  96.         }
  97.         try {
  98.             $event->setResponse($this->startAuthentication($event->getRequest(), $exception));
  99.             $event->allowCustomResponseCode();
  100.         } catch (\Exception $e) {
  101.             $event->setException($e);
  102.         }
  103.     }
  104.     private function handleAccessDeniedException(GetResponseForExceptionEvent $eventAccessDeniedException $exception)
  105.     {
  106.         $event->setException(new AccessDeniedHttpException($exception->getMessage(), $exception));
  107.         $token $this->tokenStorage->getToken();
  108.         if (!$this->authenticationTrustResolver->isFullFledged($token)) {
  109.             if (null !== $this->logger) {
  110.                 $this->logger->debug('Access denied, the user is not fully authenticated; redirecting to authentication entry point.', ['exception' => $exception]);
  111.             }
  112.             try {
  113.                 $insufficientAuthenticationException = new InsufficientAuthenticationException('Full authentication is required to access this resource.'0$exception);
  114.                 $insufficientAuthenticationException->setToken($token);
  115.                 $event->setResponse($this->startAuthentication($event->getRequest(), $insufficientAuthenticationException));
  116.             } catch (\Exception $e) {
  117.                 $event->setException($e);
  118.             }
  119.             return;
  120.         }
  121.         if (null !== $this->logger) {
  122.             $this->logger->debug('Access denied, the user is neither anonymous, nor remember-me.', ['exception' => $exception]);
  123.         }
  124.         try {
  125.             if (null !== $this->accessDeniedHandler) {
  126.                 $response $this->accessDeniedHandler->handle($event->getRequest(), $exception);
  127.                 if ($response instanceof Response) {
  128.                     $event->setResponse($response);
  129.                 }
  130.             } elseif (null !== $this->errorPage) {
  131.                 $subRequest $this->httpUtils->createRequest($event->getRequest(), $this->errorPage);
  132.                 $subRequest->attributes->set(Security::ACCESS_DENIED_ERROR$exception);
  133.                 $event->setResponse($event->getKernel()->handle($subRequestHttpKernelInterface::SUB_REQUESTtrue));
  134.                 $event->allowCustomResponseCode();
  135.             }
  136.         } catch (\Exception $e) {
  137.             if (null !== $this->logger) {
  138.                 $this->logger->error('An exception was thrown when handling an AccessDeniedException.', ['exception' => $e]);
  139.             }
  140.             $event->setException(new \RuntimeException('Exception thrown when handling an exception.'0$e));
  141.         }
  142.     }
  143.     private function handleLogoutException(LogoutException $exception): void
  144.     {
  145.         if (null !== $this->logger) {
  146.             $this->logger->info('A LogoutException was thrown.', ['exception' => $exception]);
  147.         }
  148.     }
  149.     private function startAuthentication(Request $requestAuthenticationException $authException): Response
  150.     {
  151.         if (null === $this->authenticationEntryPoint) {
  152.             throw new HttpException(Response::HTTP_UNAUTHORIZED$authException->getMessage(), $authException, [], $authException->getCode());
  153.         }
  154.         if (null !== $this->logger) {
  155.             $this->logger->debug('Calling Authentication entry point.');
  156.         }
  157.         if (!$this->stateless) {
  158.             $this->setTargetPath($request);
  159.         }
  160.         if ($authException instanceof AccountStatusException) {
  161.             // remove the security token to prevent infinite redirect loops
  162.             $this->tokenStorage->setToken(null);
  163.             if (null !== $this->logger) {
  164.                 $this->logger->info('The security token was removed due to an AccountStatusException.', ['exception' => $authException]);
  165.             }
  166.         }
  167.         $response $this->authenticationEntryPoint->start($request$authException);
  168.         if (!$response instanceof Response) {
  169.             $given = \is_object($response) ? \get_class($response) : \gettype($response);
  170.             throw new \LogicException(sprintf('The %s::start() method must return a Response object (%s returned)', \get_class($this->authenticationEntryPoint), $given));
  171.         }
  172.         return $response;
  173.     }
  174.     protected function setTargetPath(Request $request)
  175.     {
  176.         // session isn't required when using HTTP basic authentication mechanism for example
  177.         if ($request->hasSession() && $request->isMethodSafe(false) && !$request->isXmlHttpRequest()) {
  178.             $this->saveTargetPath($request->getSession(), $this->providerKey$request->getUri());
  179.         }
  180.     }
  181. }