vendor/symfony/security/Http/Firewall/ExceptionListener.php line 87

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