/src/Symfony/Component/Security/Http/Firewall/ExceptionListener.php

http://github.com/symfony/symfony · PHP · 234 lines · 168 code · 39 blank · 27 comment · 23 complexity · 5eb3c7452f47ebe3047c026695c29942 MD5 · raw file

  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\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 <fabien@symfony.com>
  38. *
  39. * @final
  40. */
  41. class ExceptionListener
  42. {
  43. use TargetPathTrait;
  44. private $tokenStorage;
  45. private $providerKey;
  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 $tokenStorage, AuthenticationTrustResolverInterface $trustResolver, HttpUtils $httpUtils, string $providerKey, AuthenticationEntryPointInterface $authenticationEntryPoint = null, string $errorPage = null, AccessDeniedHandlerInterface $accessDeniedHandler = null, LoggerInterface $logger = null, bool $stateless = false)
  54. {
  55. $this->tokenStorage = $tokenStorage;
  56. $this->accessDeniedHandler = $accessDeniedHandler;
  57. $this->httpUtils = $httpUtils;
  58. $this->providerKey = $providerKey;
  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($exception);
  100. return;
  101. }
  102. } while (null !== $exception = $exception->getPrevious());
  103. }
  104. private function handleAuthenticationException(ExceptionEvent $event, AuthenticationException $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 $event, AccessDeniedException $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($subRequest, HttpKernelInterface::SUB_REQUEST, true));
  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(LogoutException $exception): void
  158. {
  159. if (null !== $this->logger) {
  160. $this->logger->info('A LogoutException was thrown.', ['exception' => $exception]);
  161. }
  162. }
  163. private function startAuthentication(Request $request, AuthenticationException $authException): Response
  164. {
  165. if (null === $this->authenticationEntryPoint) {
  166. throw new HttpException(Response::HTTP_UNAUTHORIZED, $authException->getMessage(), $authException, [], $authException->getCode());
  167. }
  168. if (null !== $this->logger) {
  169. $this->logger->debug('Calling Authentication entry point.');
  170. }
  171. if (!$this->stateless) {
  172. $this->setTargetPath($request);
  173. }
  174. if ($authException instanceof AccountStatusException) {
  175. // remove the security token to prevent infinite redirect loops
  176. $this->tokenStorage->setToken(null);
  177. if (null !== $this->logger) {
  178. $this->logger->info('The security token was removed due to an AccountStatusException.', ['exception' => $authException]);
  179. }
  180. }
  181. $response = $this->authenticationEntryPoint->start($request, $authException);
  182. if (!$response instanceof Response) {
  183. $given = get_debug_type($response);
  184. throw new \LogicException(sprintf('The "%s::start()" method must return a Response object ("%s" returned).', get_debug_type($this->authenticationEntryPoint), $given));
  185. }
  186. return $response;
  187. }
  188. protected function setTargetPath(Request $request)
  189. {
  190. // session isn't required when using HTTP basic authentication mechanism for example
  191. if ($request->hasSession() && $request->isMethodSafe() && !$request->isXmlHttpRequest()) {
  192. $this->saveTargetPath($request->getSession(), $this->providerKey, $request->getUri());
  193. }
  194. }
  195. }