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

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