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.                 $this->handleAuthenticationException($event$exception);
  87.                 return;
  88.             }
  89.             if ($exception instanceof AccessDeniedException) {
  90.                 $this->handleAccessDeniedException($event$exception);
  91.                 return;
  92.             }
  93.             if ($exception instanceof LogoutException) {
  94.                 $this->handleLogoutException($exception);
  95.                 return;
  96.             }
  97.         } while (null !== $exception $exception->getPrevious());
  98.     }
  99.     private function handleAuthenticationException(GetResponseForExceptionEvent $eventAuthenticationException $exception): void
  100.     {
  101.         if (null !== $this->logger) {
  102.             $this->logger->info('An AuthenticationException was thrown; redirecting to authentication entry point.', ['exception' => $exception]);
  103.         }
  104.         try {
  105.             $event->setResponse($this->startAuthentication($event->getRequest(), $exception));
  106.             $event->allowCustomResponseCode();
  107.         } catch (\Exception $e) {
  108.             $event->setException($e);
  109.         }
  110.     }
  111.     private function handleAccessDeniedException(GetResponseForExceptionEvent $eventAccessDeniedException $exception)
  112.     {
  113.         $event->setException(new AccessDeniedHttpException($exception->getMessage(), $exception));
  114.         $token $this->tokenStorage->getToken();
  115.         if (!$this->authenticationTrustResolver->isFullFledged($token)) {
  116.             if (null !== $this->logger) {
  117.                 $this->logger->debug('Access denied, the user is not fully authenticated; redirecting to authentication entry point.', ['exception' => $exception]);
  118.             }
  119.             try {
  120.                 $insufficientAuthenticationException = new InsufficientAuthenticationException('Full authentication is required to access this resource.'0$exception);
  121.                 $insufficientAuthenticationException->setToken($token);
  122.                 $event->setResponse($this->startAuthentication($event->getRequest(), $insufficientAuthenticationException));
  123.             } catch (\Exception $e) {
  124.                 $event->setException($e);
  125.             }
  126.             return;
  127.         }
  128.         if (null !== $this->logger) {
  129.             $this->logger->debug('Access denied, the user is neither anonymous, nor remember-me.', ['exception' => $exception]);
  130.         }
  131.         try {
  132.             if (null !== $this->accessDeniedHandler) {
  133.                 $response $this->accessDeniedHandler->handle($event->getRequest(), $exception);
  134.                 if ($response instanceof Response) {
  135.                     $event->setResponse($response);
  136.                 }
  137.             } elseif (null !== $this->errorPage) {
  138.                 $subRequest $this->httpUtils->createRequest($event->getRequest(), $this->errorPage);
  139.                 $subRequest->attributes->set(Security::ACCESS_DENIED_ERROR$exception);
  140.                 $event->setResponse($event->getKernel()->handle($subRequestHttpKernelInterface::SUB_REQUESTtrue));
  141.                 $event->allowCustomResponseCode();
  142.             }
  143.         } catch (\Exception $e) {
  144.             if (null !== $this->logger) {
  145.                 $this->logger->error('An exception was thrown when handling an AccessDeniedException.', ['exception' => $e]);
  146.             }
  147.             $event->setException(new \RuntimeException('Exception thrown when handling an exception.'0$e));
  148.         }
  149.     }
  150.     private function handleLogoutException(LogoutException $exception): void
  151.     {
  152.         if (null !== $this->logger) {
  153.             $this->logger->info('A LogoutException was thrown.', ['exception' => $exception]);
  154.         }
  155.     }
  156.     private function startAuthentication(Request $requestAuthenticationException $authException): Response
  157.     {
  158.         if (null === $this->authenticationEntryPoint) {
  159.             throw new HttpException(Response::HTTP_UNAUTHORIZED$authException->getMessage(), $authException, [], $authException->getCode());
  160.         }
  161.         if (null !== $this->logger) {
  162.             $this->logger->debug('Calling Authentication entry point.');
  163.         }
  164.         if (!$this->stateless) {
  165.             $this->setTargetPath($request);
  166.         }
  167.         if ($authException instanceof AccountStatusException) {
  168.             // remove the security token to prevent infinite redirect loops
  169.             $this->tokenStorage->setToken(null);
  170.             if (null !== $this->logger) {
  171.                 $this->logger->info('The security token was removed due to an AccountStatusException.', ['exception' => $authException]);
  172.             }
  173.         }
  174.         $response $this->authenticationEntryPoint->start($request$authException);
  175.         if (!$response instanceof Response) {
  176.             $given = \is_object($response) ? \get_class($response) : \gettype($response);
  177.             throw new \LogicException(sprintf('The %s::start() method must return a Response object (%s returned)', \get_class($this->authenticationEntryPoint), $given));
  178.         }
  179.         return $response;
  180.     }
  181.     protected function setTargetPath(Request $request)
  182.     {
  183.         // session isn't required when using HTTP basic authentication mechanism for example
  184.         if ($request->hasSession() && $request->isMethodSafe(false) && !$request->isXmlHttpRequest()) {
  185.             $this->saveTargetPath($request->getSession(), $this->providerKey$request->getUri());
  186.         }
  187.     }
  188. }