GuardAuthenticatorHandler.php 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  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\Guard;
  11. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\HttpFoundation\Response;
  14. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  15. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  16. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  17. use Symfony\Component\Security\Core\User\UserInterface;
  18. use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
  19. use Symfony\Component\Security\Http\SecurityEvents;
  20. use Symfony\Component\Security\Http\Session\SessionAuthenticationStrategyInterface;
  21. /**
  22. * A utility class that does much of the *work* during the guard authentication process.
  23. *
  24. * By having the logic here instead of the listener, more of the process
  25. * can be called directly (e.g. for manual authentication) or overridden.
  26. *
  27. * @author Ryan Weaver <ryan@knpuniversity.com>
  28. */
  29. class GuardAuthenticatorHandler
  30. {
  31. private $tokenStorage;
  32. private $dispatcher;
  33. private $sessionStrategy;
  34. private $statelessProviderKeys;
  35. /**
  36. * @param array $statelessProviderKeys An array of provider/firewall keys that are "stateless" and so do not need the session migrated on success
  37. */
  38. public function __construct(TokenStorageInterface $tokenStorage, EventDispatcherInterface $eventDispatcher = null, array $statelessProviderKeys = array())
  39. {
  40. $this->tokenStorage = $tokenStorage;
  41. $this->dispatcher = $eventDispatcher;
  42. $this->statelessProviderKeys = $statelessProviderKeys;
  43. }
  44. /**
  45. * Authenticates the given token in the system.
  46. *
  47. * @param string $providerKey The name of the provider/firewall being used for authentication
  48. */
  49. public function authenticateWithToken(TokenInterface $token, Request $request/*, string $providerKey */)
  50. {
  51. $providerKey = \func_num_args() > 2 ? func_get_arg(2) : null;
  52. $this->migrateSession($request, $token, $providerKey);
  53. $this->tokenStorage->setToken($token);
  54. if (null !== $this->dispatcher) {
  55. $loginEvent = new InteractiveLoginEvent($request, $token);
  56. $this->dispatcher->dispatch(SecurityEvents::INTERACTIVE_LOGIN, $loginEvent);
  57. }
  58. }
  59. /**
  60. * Returns the "on success" response for the given GuardAuthenticator.
  61. *
  62. * @param TokenInterface $token
  63. * @param Request $request
  64. * @param GuardAuthenticatorInterface $guardAuthenticator
  65. * @param string $providerKey The provider (i.e. firewall) key
  66. *
  67. * @return Response|null
  68. */
  69. public function handleAuthenticationSuccess(TokenInterface $token, Request $request, GuardAuthenticatorInterface $guardAuthenticator, $providerKey)
  70. {
  71. $response = $guardAuthenticator->onAuthenticationSuccess($request, $token, $providerKey);
  72. // check that it's a Response or null
  73. if ($response instanceof Response || null === $response) {
  74. return $response;
  75. }
  76. throw new \UnexpectedValueException(sprintf('The %s::onAuthenticationSuccess method must return null or a Response object. You returned %s.', \get_class($guardAuthenticator), \is_object($response) ? \get_class($response) : \gettype($response)));
  77. }
  78. /**
  79. * Convenience method for authenticating the user and returning the
  80. * Response *if any* for success.
  81. *
  82. * @param UserInterface $user
  83. * @param Request $request
  84. * @param GuardAuthenticatorInterface $authenticator
  85. * @param string $providerKey The provider (i.e. firewall) key
  86. *
  87. * @return Response|null
  88. */
  89. public function authenticateUserAndHandleSuccess(UserInterface $user, Request $request, GuardAuthenticatorInterface $authenticator, $providerKey)
  90. {
  91. // create an authenticated token for the User
  92. $token = $authenticator->createAuthenticatedToken($user, $providerKey);
  93. // authenticate this in the system
  94. $this->authenticateWithToken($token, $request, $providerKey);
  95. // return the success metric
  96. return $this->handleAuthenticationSuccess($token, $request, $authenticator, $providerKey);
  97. }
  98. /**
  99. * Handles an authentication failure and returns the Response for the
  100. * GuardAuthenticator.
  101. *
  102. * @param AuthenticationException $authenticationException
  103. * @param Request $request
  104. * @param GuardAuthenticatorInterface $guardAuthenticator
  105. * @param string $providerKey The key of the firewall
  106. *
  107. * @return Response|null
  108. */
  109. public function handleAuthenticationFailure(AuthenticationException $authenticationException, Request $request, GuardAuthenticatorInterface $guardAuthenticator, $providerKey)
  110. {
  111. $response = $guardAuthenticator->onAuthenticationFailure($request, $authenticationException);
  112. if ($response instanceof Response || null === $response) {
  113. // returning null is ok, it means they want the request to continue
  114. return $response;
  115. }
  116. throw new \UnexpectedValueException(sprintf('The %s::onAuthenticationFailure method must return null or a Response object. You returned %s.', \get_class($guardAuthenticator), \is_object($response) ? \get_class($response) : \gettype($response)));
  117. }
  118. /**
  119. * Call this method if your authentication token is stored to a session.
  120. *
  121. * @final
  122. */
  123. public function setSessionAuthenticationStrategy(SessionAuthenticationStrategyInterface $sessionStrategy)
  124. {
  125. $this->sessionStrategy = $sessionStrategy;
  126. }
  127. private function migrateSession(Request $request, TokenInterface $token, $providerKey)
  128. {
  129. if (!$this->sessionStrategy || !$request->hasSession() || !$request->hasPreviousSession() || \in_array($providerKey, $this->statelessProviderKeys, true)) {
  130. return;
  131. }
  132. $this->sessionStrategy->onAuthentication($request, $token);
  133. }
  134. }