vendor/symfony/symfony/src/Symfony/Component/Security/Http/Firewall/ExceptionListener.php line 92

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