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.                 return $this->handleAuthenticationException($event$exception);
  85.             } elseif ($exception instanceof AccessDeniedException) {
  86.                 return $this->handleAccessDeniedException($event$exception);
  87.             } elseif ($exception instanceof LogoutException) {
  88.                 return $this->handleLogoutException($exception);
  89.             }
  90.         } while (null !== $exception $exception->getPrevious());
  91.     }
  92.     private function handleAuthenticationException(GetResponseForExceptionEvent $eventAuthenticationException $exception)
  93.     {
  94.         if (null !== $this->logger) {
  95.             $this->logger->info('An AuthenticationException was thrown; redirecting to authentication entry point.', ['exception' => $exception]);
  96.         }
  97.         try {
  98.             $event->setResponse($this->startAuthentication($event->getRequest(), $exception));
  99.             $event->allowCustomResponseCode();
  100.         } catch (\Exception $e) {
  101.             $event->setException($e);
  102.         }
  103.     }
  104.     private function handleAccessDeniedException(GetResponseForExceptionEvent $eventAccessDeniedException $exception)
  105.     {
  106.         $event->setException(new AccessDeniedHttpException($exception->getMessage(), $exception));
  107.         $token $this->tokenStorage->getToken();
  108.         if (!$this->authenticationTrustResolver->isFullFledged($token)) {
  109.             if (null !== $this->logger) {
  110.                 $this->logger->debug('Access denied, the user is not fully authenticated; redirecting to authentication entry point.', ['exception' => $exception]);
  111.             }
  112.             try {
  113.                 $insufficientAuthenticationException = new InsufficientAuthenticationException('Full authentication is required to access this resource.'0$exception);
  114.                 $insufficientAuthenticationException->setToken($token);
  115.                 $event->setResponse($this->startAuthentication($event->getRequest(), $insufficientAuthenticationException));
  116.             } catch (\Exception $e) {
  117.                 $event->setException($e);
  118.             }
  119.             return;
  120.         }
  121.         if (null !== $this->logger) {
  122.             $this->logger->debug('Access denied, the user is neither anonymous, nor remember-me.', ['exception' => $exception]);
  123.         }
  124.         try {
  125.             if (null !== $this->accessDeniedHandler) {
  126.                 $response $this->accessDeniedHandler->handle($event->getRequest(), $exception);
  127.                 if ($response instanceof Response) {
  128.                     $event->setResponse($response);
  129.                 }
  130.             } elseif (null !== $this->errorPage) {
  131.                 $subRequest $this->httpUtils->createRequest($event->getRequest(), $this->errorPage);
  132.                 $subRequest->attributes->set(Security::ACCESS_DENIED_ERROR$exception);
  133.                 $event->setResponse($event->getKernel()->handle($subRequestHttpKernelInterface::SUB_REQUESTtrue));
  134.                 $event->allowCustomResponseCode();
  135.             }
  136.         } catch (\Exception $e) {
  137.             if (null !== $this->logger) {
  138.                 $this->logger->error('An exception was thrown when handling an AccessDeniedException.', ['exception' => $e]);
  139.             }
  140.             $event->setException(new \RuntimeException('Exception thrown when handling an exception.'0$e));
  141.         }
  142.     }
  143.     private function handleLogoutException(LogoutException $exception)
  144.     {
  145.         if (null !== $this->logger) {
  146.             $this->logger->info('A LogoutException was thrown.', ['exception' => $exception]);
  147.         }
  148.     }
  149.     /**
  150.      * @return Response
  151.      *
  152.      * @throws AuthenticationException
  153.      */
  154.     private function startAuthentication(Request $requestAuthenticationException $authException)
  155.     {
  156.         if (null === $this->authenticationEntryPoint) {
  157.             throw new HttpException(Response::HTTP_UNAUTHORIZED$authException->getMessage(), $authException, [], $authException->getCode());
  158.         }
  159.         if (null !== $this->logger) {
  160.             $this->logger->debug('Calling Authentication entry point.');
  161.         }
  162.         if (!$this->stateless) {
  163.             $this->setTargetPath($request);
  164.         }
  165.         if ($authException instanceof AccountStatusException) {
  166.             // remove the security token to prevent infinite redirect loops
  167.             $this->tokenStorage->setToken(null);
  168.             if (null !== $this->logger) {
  169.                 $this->logger->info('The security token was removed due to an AccountStatusException.', ['exception' => $authException]);
  170.             }
  171.         }
  172.         $response $this->authenticationEntryPoint->start($request$authException);
  173.         if (!$response instanceof Response) {
  174.             $given = \is_object($response) ? \get_class($response) : \gettype($response);
  175.             throw new \LogicException(sprintf('The %s::start() method must return a Response object (%s returned)', \get_class($this->authenticationEntryPoint), $given));
  176.         }
  177.         return $response;
  178.     }
  179.     protected function setTargetPath(Request $request)
  180.     {
  181.         // session isn't required when using HTTP basic authentication mechanism for example
  182.         if ($request->hasSession() && $request->isMethodSafe(false) && !$request->isXmlHttpRequest()) {
  183.             $this->saveTargetPath($request->getSession(), $this->providerKey$request->getUri());
  184.         }
  185.     }
  186. }