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

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