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

  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\Http\Authorization\AccessDeniedHandlerInterface;
  29. use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;
  30. use Symfony\Component\Security\Http\EntryPoint\Exception\NotAnEntryPointException;
  31. use Symfony\Component\Security\Http\HttpUtils;
  32. use Symfony\Component\Security\Http\SecurityRequestAttributes;
  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 TokenStorageInterface $tokenStorage;
  46. private string $firewallName;
  47. private ?AccessDeniedHandlerInterface $accessDeniedHandler;
  48. private ?AuthenticationEntryPointInterface $authenticationEntryPoint;
  49. private AuthenticationTrustResolverInterface $authenticationTrustResolver;
  50. private ?string $errorPage;
  51. private ?LoggerInterface $logger;
  52. private HttpUtils $httpUtils;
  53. private bool $stateless;
  54. public function __construct(TokenStorageInterface $tokenStorage, AuthenticationTrustResolverInterface $trustResolver, HttpUtils $httpUtils, string $firewallName, ?AuthenticationEntryPointInterface $authenticationEntryPoint = null, ?string $errorPage = null, ?AccessDeniedHandlerInterface $accessDeniedHandler = null, ?LoggerInterface $logger = null, bool $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): void
  70. {
  71. $dispatcher->addListener(KernelEvents::EXCEPTION, $this->onKernelException(...), 1);
  72. }
  73. /**
  74. * Unregisters the dispatcher.
  75. */
  76. public function unregister(EventDispatcherInterface $dispatcher): void
  77. {
  78. $dispatcher->removeListener(KernelEvents::EXCEPTION, $this->onKernelException(...));
  79. }
  80. /**
  81. * Handles security related exceptions.
  82. */
  83. public function onKernelException(ExceptionEvent $event): void
  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 $event, AuthenticationException $exception): void
  106. {
  107. $this->logger?->info('An AuthenticationException was thrown; redirecting to authentication entry point.', ['exception' => $exception]);
  108. try {
  109. $event->setResponse($this->startAuthentication($event->getRequest(), $exception));
  110. $event->allowCustomResponseCode();
  111. } catch (\Exception $e) {
  112. $event->setThrowable($e);
  113. }
  114. }
  115. private function handleAccessDeniedException(ExceptionEvent $event, AccessDeniedException $exception): void
  116. {
  117. $event->setThrowable(new AccessDeniedHttpException($exception->getMessage(), $exception));
  118. $token = $this->tokenStorage->getToken();
  119. if (!$this->authenticationTrustResolver->isFullFledged($token)) {
  120. $this->logger?->debug('Access denied, the user is not fully authenticated; redirecting to authentication entry point.', ['exception' => $exception]);
  121. try {
  122. $insufficientAuthenticationException = new InsufficientAuthenticationException('Full authentication is required to access this resource.', 0, $exception);
  123. if (null !== $token) {
  124. $insufficientAuthenticationException->setToken($token);
  125. }
  126. $event->setResponse($this->startAuthentication($event->getRequest(), $insufficientAuthenticationException));
  127. } catch (\Exception $e) {
  128. $event->setThrowable($e);
  129. }
  130. return;
  131. }
  132. $this->logger?->debug('Access denied, the user is neither anonymous, nor remember-me.', ['exception' => $exception]);
  133. try {
  134. if (null !== $this->accessDeniedHandler) {
  135. $response = $this->accessDeniedHandler->handle($event->getRequest(), $exception);
  136. if ($response instanceof Response) {
  137. $event->setResponse($response);
  138. }
  139. } elseif (null !== $this->errorPage) {
  140. $subRequest = $this->httpUtils->createRequest($event->getRequest(), $this->errorPage);
  141. $subRequest->attributes->set(SecurityRequestAttributes::ACCESS_DENIED_ERROR, $exception);
  142. $event->setResponse($event->getKernel()->handle($subRequest, HttpKernelInterface::SUB_REQUEST, true));
  143. $event->allowCustomResponseCode();
  144. }
  145. } catch (\Exception $e) {
  146. $this->logger?->error('An exception was thrown when handling an AccessDeniedException.', ['exception' => $e]);
  147. $event->setThrowable(new \RuntimeException('Exception thrown when handling an exception.', 0, $e));
  148. }
  149. }
  150. private function handleLogoutException(ExceptionEvent $event, LogoutException $exception): void
  151. {
  152. $event->setThrowable(new AccessDeniedHttpException($exception->getMessage(), $exception));
  153. $this->logger?->info('A LogoutException was thrown; wrapping with AccessDeniedHttpException', ['exception' => $exception]);
  154. }
  155. private function startAuthentication(Request $request, AuthenticationException $authException): Response
  156. {
  157. if (null === $this->authenticationEntryPoint) {
  158. $this->throwUnauthorizedException($authException);
  159. }
  160. $this->logger?->debug('Calling Authentication entry point.', ['entry_point' => $this->authenticationEntryPoint]);
  161. if (!$this->stateless) {
  162. $this->setTargetPath($request);
  163. }
  164. if ($authException instanceof AccountStatusException) {
  165. // remove the security token to prevent infinite redirect loops
  166. $this->tokenStorage->setToken(null);
  167. $this->logger?->info('The security token was removed due to an AccountStatusException.', ['exception' => $authException]);
  168. }
  169. try {
  170. $response = $this->authenticationEntryPoint->start($request, $authException);
  171. } catch (NotAnEntryPointException) {
  172. $this->throwUnauthorizedException($authException);
  173. }
  174. if (!$response instanceof Response) {
  175. $given = get_debug_type($response);
  176. throw new \LogicException(sprintf('The "%s::start()" method must return a Response object ("%s" returned).', get_debug_type($this->authenticationEntryPoint), $given));
  177. }
  178. return $response;
  179. }
  180. protected function setTargetPath(Request $request): void
  181. {
  182. // session isn't required when using HTTP basic authentication mechanism for example
  183. if ($request->hasSession() && $request->isMethodSafe() && !$request->isXmlHttpRequest()) {
  184. $this->saveTargetPath($request->getSession(), $this->firewallName, $request->getUri());
  185. }
  186. }
  187. private function throwUnauthorizedException(AuthenticationException $authException): never
  188. {
  189. $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));
  190. throw new HttpException(Response::HTTP_UNAUTHORIZED, $authException->getMessage(), $authException, [], $authException->getCode());
  191. }
  192. }