GuardAuthenticatorHandler.php 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  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\HttpFoundation\Request;
  12. use Symfony\Component\HttpFoundation\Response;
  13. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  14. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  15. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  16. use Symfony\Component\Security\Core\User\UserInterface;
  17. use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
  18. use Symfony\Component\Security\Http\SecurityEvents;
  19. use Symfony\Component\Security\Http\Session\SessionAuthenticationStrategyInterface;
  20. use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
  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. * @final
  30. */
  31. class GuardAuthenticatorHandler
  32. {
  33. private $tokenStorage;
  34. private $dispatcher;
  35. private $sessionStrategy;
  36. private $statelessProviderKeys;
  37. /**
  38. * @param array $statelessProviderKeys An array of provider/firewall keys that are "stateless" and so do not need the session migrated on success
  39. */
  40. public function __construct(TokenStorageInterface $tokenStorage, EventDispatcherInterface $eventDispatcher = null, array $statelessProviderKeys = [])
  41. {
  42. $this->tokenStorage = $tokenStorage;
  43. $this->dispatcher = $eventDispatcher;
  44. $this->statelessProviderKeys = $statelessProviderKeys;
  45. }
  46. /**
  47. * Authenticates the given token in the system.
  48. */
  49. public function authenticateWithToken(TokenInterface $token, Request $request, string $providerKey = null)
  50. {
  51. $this->migrateSession($request, $token, $providerKey);
  52. $this->tokenStorage->setToken($token);
  53. if (null !== $this->dispatcher) {
  54. $loginEvent = new InteractiveLoginEvent($request, $token);
  55. $this->dispatcher->dispatch($loginEvent, SecurityEvents::INTERACTIVE_LOGIN);
  56. }
  57. }
  58. /**
  59. * Returns the "on success" response for the given GuardAuthenticator.
  60. */
  61. public function handleAuthenticationSuccess(TokenInterface $token, Request $request, AuthenticatorInterface $guardAuthenticator, string $providerKey): ?Response
  62. {
  63. $response = $guardAuthenticator->onAuthenticationSuccess($request, $token, $providerKey);
  64. // check that it's a Response or null
  65. if ($response instanceof Response || null === $response) {
  66. return $response;
  67. }
  68. throw new \UnexpectedValueException(sprintf('The "%s::onAuthenticationSuccess()" method must return null or a Response object. You returned "%s".', \get_class($guardAuthenticator), get_debug_type($response)));
  69. }
  70. /**
  71. * Convenience method for authenticating the user and returning the
  72. * Response *if any* for success.
  73. */
  74. public function authenticateUserAndHandleSuccess(UserInterface $user, Request $request, AuthenticatorInterface $authenticator, string $providerKey): ?Response
  75. {
  76. // create an authenticated token for the User
  77. $token = $authenticator->createAuthenticatedToken($user, $providerKey);
  78. // authenticate this in the system
  79. $this->authenticateWithToken($token, $request, $providerKey);
  80. // return the success metric
  81. return $this->handleAuthenticationSuccess($token, $request, $authenticator, $providerKey);
  82. }
  83. /**
  84. * Handles an authentication failure and returns the Response for the
  85. * GuardAuthenticator.
  86. */
  87. public function handleAuthenticationFailure(AuthenticationException $authenticationException, Request $request, AuthenticatorInterface $guardAuthenticator, string $providerKey): ?Response
  88. {
  89. $response = $guardAuthenticator->onAuthenticationFailure($request, $authenticationException);
  90. if ($response instanceof Response || null === $response) {
  91. // returning null is ok, it means they want the request to continue
  92. return $response;
  93. }
  94. throw new \UnexpectedValueException(sprintf('The "%s::onAuthenticationFailure()" method must return null or a Response object. You returned "%s".', \get_class($guardAuthenticator), get_debug_type($response)));
  95. }
  96. /**
  97. * Call this method if your authentication token is stored to a session.
  98. *
  99. * @final
  100. */
  101. public function setSessionAuthenticationStrategy(SessionAuthenticationStrategyInterface $sessionStrategy)
  102. {
  103. $this->sessionStrategy = $sessionStrategy;
  104. }
  105. private function migrateSession(Request $request, TokenInterface $token, ?string $providerKey)
  106. {
  107. if (\in_array($providerKey, $this->statelessProviderKeys, true) || !$this->sessionStrategy || !$request->hasSession() || !$request->hasPreviousSession()) {
  108. return;
  109. }
  110. $this->sessionStrategy->onAuthentication($request, $token);
  111. }
  112. }