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

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