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

https://github.com/Exercise/symfony · PHP · 186 lines · 131 code · 28 blank · 27 comment · 17 complexity · a44fa523330dc006750db1b65585eb1d 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 Symfony\Component\HttpFoundation\Response;
  12. use Symfony\Component\Security\Http\Authorization\AccessDeniedHandlerInterface;
  13. use Symfony\Component\Security\Core\SecurityContextInterface;
  14. use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface;
  15. use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;
  16. use Symfony\Component\Security\Core\Exception\AccountStatusException;
  17. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  18. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  19. use Symfony\Component\Security\Core\Exception\InsufficientAuthenticationException;
  20. use Symfony\Component\Security\Core\Exception\LogoutException;
  21. use Symfony\Component\Security\Http\HttpUtils;
  22. use Symfony\Component\HttpFoundation\Request;
  23. use Symfony\Component\HttpKernel\Log\LoggerInterface;
  24. use Symfony\Component\HttpKernel\HttpKernelInterface;
  25. use Symfony\Component\HttpKernel\KernelEvents;
  26. use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
  27. use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
  28. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  29. /**
  30. * ExceptionListener catches authentication exception and converts them to
  31. * Response instances.
  32. *
  33. * @author Fabien Potencier <fabien@symfony.com>
  34. */
  35. class ExceptionListener
  36. {
  37. private $context;
  38. private $accessDeniedHandler;
  39. private $authenticationEntryPoint;
  40. private $authenticationTrustResolver;
  41. private $errorPage;
  42. private $logger;
  43. private $httpUtils;
  44. public function __construct(SecurityContextInterface $context, AuthenticationTrustResolverInterface $trustResolver, HttpUtils $httpUtils, AuthenticationEntryPointInterface $authenticationEntryPoint = null, $errorPage = null, AccessDeniedHandlerInterface $accessDeniedHandler = null, LoggerInterface $logger = null)
  45. {
  46. $this->context = $context;
  47. $this->accessDeniedHandler = $accessDeniedHandler;
  48. $this->httpUtils = $httpUtils;
  49. $this->authenticationEntryPoint = $authenticationEntryPoint;
  50. $this->authenticationTrustResolver = $trustResolver;
  51. $this->errorPage = $errorPage;
  52. $this->logger = $logger;
  53. }
  54. /**
  55. * Registers a onKernelException listener to take care of security exceptions.
  56. *
  57. * @param EventDispatcherInterface $dispatcher An EventDispatcherInterface instance
  58. */
  59. public function register(EventDispatcherInterface $dispatcher)
  60. {
  61. $dispatcher->addListener(KernelEvents::EXCEPTION, array($this, 'onKernelException'));
  62. }
  63. /**
  64. * Handles security related exceptions.
  65. *
  66. * @param GetResponseForExceptionEvent $event An GetResponseForExceptionEvent instance
  67. */
  68. public function onKernelException(GetResponseForExceptionEvent $event)
  69. {
  70. $exception = $event->getException();
  71. $request = $event->getRequest();
  72. // determine the actual cause for the exception
  73. while (null !== $previous = $exception->getPrevious()) {
  74. $exception = $previous;
  75. }
  76. if ($exception instanceof AuthenticationException) {
  77. if (null !== $this->logger) {
  78. $this->logger->info(sprintf('Authentication exception occurred; redirecting to authentication entry point (%s)', $exception->getMessage()));
  79. }
  80. try {
  81. $response = $this->startAuthentication($request, $exception);
  82. } catch (\Exception $e) {
  83. $event->setException($e);
  84. return;
  85. }
  86. } elseif ($exception instanceof AccessDeniedException) {
  87. $token = $this->context->getToken();
  88. if (!$this->authenticationTrustResolver->isFullFledged($token)) {
  89. if (null !== $this->logger) {
  90. $this->logger->debug(sprintf('Access is denied (user is not fully authenticated) by "%s" at line %s; redirecting to authentication entry point', $exception->getFile(), $exception->getLine()));
  91. }
  92. try {
  93. $response = $this->startAuthentication($request, new InsufficientAuthenticationException('Full authentication is required to access this resource.', $token, 0, $exception));
  94. } catch (\Exception $e) {
  95. $event->setException($e);
  96. return;
  97. }
  98. } else {
  99. if (null !== $this->logger) {
  100. $this->logger->debug(sprintf('Access is denied (and user is neither anonymous, nor remember-me) by "%s" at line %s', $exception->getFile(), $exception->getLine()));
  101. }
  102. try {
  103. if (null !== $this->accessDeniedHandler) {
  104. $response = $this->accessDeniedHandler->handle($request, $exception);
  105. if (!$response instanceof Response) {
  106. return;
  107. }
  108. } elseif (null !== $this->errorPage) {
  109. $subRequest = $this->httpUtils->createRequest($request, $this->errorPage);
  110. $subRequest->attributes->set(SecurityContextInterface::ACCESS_DENIED_ERROR, $exception);
  111. $response = $event->getKernel()->handle($subRequest, HttpKernelInterface::SUB_REQUEST, true);
  112. $response->setStatusCode(403);
  113. } else {
  114. $event->setException(new AccessDeniedHttpException($exception->getMessage(), $exception));
  115. return;
  116. }
  117. } catch (\Exception $e) {
  118. if (null !== $this->logger) {
  119. $this->logger->err(sprintf('Exception thrown when handling an exception (%s: %s)', get_class($e), $e->getMessage()));
  120. }
  121. $event->setException(new \RuntimeException('Exception thrown when handling an exception.', 0, $e));
  122. return;
  123. }
  124. }
  125. } elseif ($exception instanceof LogoutException) {
  126. if (null !== $this->logger) {
  127. $this->logger->info(sprintf('Logout exception occurred; wrapping with AccessDeniedHttpException (%s)', $exception->getMessage()));
  128. }
  129. $event->setException(new AccessDeniedHttpException($exception->getMessage(), $exception));
  130. return;
  131. } else {
  132. return;
  133. }
  134. $event->setResponse($response);
  135. }
  136. private function startAuthentication(Request $request, AuthenticationException $authException)
  137. {
  138. if (null === $this->authenticationEntryPoint) {
  139. throw $authException;
  140. }
  141. if (null !== $this->logger) {
  142. $this->logger->debug('Calling Authentication entry point');
  143. }
  144. $this->setTargetPath($request);
  145. if ($authException instanceof AccountStatusException) {
  146. // remove the security token to prevent infinite redirect loops
  147. $this->context->setToken(null);
  148. }
  149. return $this->authenticationEntryPoint->start($request, $authException);
  150. }
  151. protected function setTargetPath(Request $request)
  152. {
  153. // session isn't required when using http basic authentication mechanism for example
  154. if ($request->hasSession()) {
  155. $request->getSession()->set('_security.target_path', $request->getUri());
  156. }
  157. }
  158. }