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

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