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

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