vendor/symfony/security-http/Authentication/AuthenticatorManager.php line 124

Open in your IDE?
  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\Authentication;
  11. use Psr\Log\LoggerInterface;
  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\AuthenticationEvents;
  17. use Symfony\Component\Security\Core\Event\AuthenticationSuccessEvent;
  18. use Symfony\Component\Security\Core\Exception\AccountStatusException;
  19. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  20. use Symfony\Component\Security\Core\Exception\BadCredentialsException;
  21. use Symfony\Component\Security\Core\Exception\CustomUserMessageAccountStatusException;
  22. use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
  23. use Symfony\Component\Security\Core\User\UserInterface;
  24. use Symfony\Component\Security\Http\Authenticator\AuthenticatorInterface;
  25. use Symfony\Component\Security\Http\Authenticator\InteractiveAuthenticatorInterface;
  26. use Symfony\Component\Security\Http\Authenticator\Passport\Badge\BadgeInterface;
  27. use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
  28. use Symfony\Component\Security\Http\Authenticator\Passport\PassportInterface;
  29. use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
  30. use Symfony\Component\Security\Http\Event\AuthenticationTokenCreatedEvent;
  31. use Symfony\Component\Security\Http\Event\CheckPassportEvent;
  32. use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
  33. use Symfony\Component\Security\Http\Event\LoginFailureEvent;
  34. use Symfony\Component\Security\Http\Event\LoginSuccessEvent;
  35. use Symfony\Component\Security\Http\SecurityEvents;
  36. use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
  37. /**
  38.  * @author Wouter de Jong <wouter@wouterj.nl>
  39.  * @author Ryan Weaver <ryan@symfonycasts.com>
  40.  * @author Amaury Leroux de Lens <amaury@lerouxdelens.com>
  41.  */
  42. class AuthenticatorManager implements AuthenticatorManagerInterfaceUserAuthenticatorInterface
  43. {
  44.     private $authenticators;
  45.     private $tokenStorage;
  46.     private $eventDispatcher;
  47.     private $eraseCredentials;
  48.     private $logger;
  49.     private $firewallName;
  50.     private $hideUserNotFoundExceptions;
  51.     private $requiredBadges;
  52.     /**
  53.      * @param AuthenticatorInterface[] $authenticators
  54.      */
  55.     public function __construct(iterable $authenticatorsTokenStorageInterface $tokenStorageEventDispatcherInterface $eventDispatcherstring $firewallNameLoggerInterface $logger nullbool $eraseCredentials truebool $hideUserNotFoundExceptions true, array $requiredBadges = [])
  56.     {
  57.         $this->authenticators $authenticators;
  58.         $this->tokenStorage $tokenStorage;
  59.         $this->eventDispatcher $eventDispatcher;
  60.         $this->firewallName $firewallName;
  61.         $this->logger $logger;
  62.         $this->eraseCredentials $eraseCredentials;
  63.         $this->hideUserNotFoundExceptions $hideUserNotFoundExceptions;
  64.         $this->requiredBadges $requiredBadges;
  65.     }
  66.     /**
  67.      * @param BadgeInterface[] $badges Optionally, pass some Passport badges to use for the manual login
  68.      */
  69.     public function authenticateUser(UserInterface $userAuthenticatorInterface $authenticatorRequest $request, array $badges = []): ?Response
  70.     {
  71.         // create an authenticated token for the User
  72.         // @deprecated since Symfony 5.3, change to $user->getUserIdentifier() in 6.0
  73.         $token $authenticator->createAuthenticatedToken($passport = new SelfValidatingPassport(new UserBadge(method_exists($user'getUserIdentifier') ? $user->getUserIdentifier() : $user->getUsername(), function () use ($user) { return $user; }), $badges), $this->firewallName);
  74.         // announce the authenticated token
  75.         $token $this->eventDispatcher->dispatch(new AuthenticationTokenCreatedEvent($token$passport))->getAuthenticatedToken();
  76.         // authenticate this in the system
  77.         return $this->handleAuthenticationSuccess($token$passport$request$authenticator);
  78.     }
  79.     public function supports(Request $request): ?bool
  80.     {
  81.         if (null !== $this->logger) {
  82.             $context = ['firewall_name' => $this->firewallName];
  83.             if ($this->authenticators instanceof \Countable || \is_array($this->authenticators)) {
  84.                 $context['authenticators'] = \count($this->authenticators);
  85.             }
  86.             $this->logger->debug('Checking for authenticator support.'$context);
  87.         }
  88.         $authenticators = [];
  89.         $lazy true;
  90.         foreach ($this->authenticators as $authenticator) {
  91.             if (null !== $this->logger) {
  92.                 $this->logger->debug('Checking support on authenticator.', ['firewall_name' => $this->firewallName'authenticator' => \get_class($authenticator)]);
  93.             }
  94.             if (false !== $supports $authenticator->supports($request)) {
  95.                 $authenticators[] = $authenticator;
  96.                 $lazy $lazy && null === $supports;
  97.             } elseif (null !== $this->logger) {
  98.                 $this->logger->debug('Authenticator does not support the request.', ['firewall_name' => $this->firewallName'authenticator' => \get_class($authenticator)]);
  99.             }
  100.         }
  101.         if (!$authenticators) {
  102.             return false;
  103.         }
  104.         $request->attributes->set('_security_authenticators'$authenticators);
  105.         return $lazy null true;
  106.     }
  107.     public function authenticateRequest(Request $request): ?Response
  108.     {
  109.         $authenticators $request->attributes->get('_security_authenticators');
  110.         $request->attributes->remove('_security_authenticators');
  111.         if (!$authenticators) {
  112.             return null;
  113.         }
  114.         return $this->executeAuthenticators($authenticators$request);
  115.     }
  116.     /**
  117.      * @param AuthenticatorInterface[] $authenticators
  118.      */
  119.     private function executeAuthenticators(array $authenticatorsRequest $request): ?Response
  120.     {
  121.         foreach ($authenticators as $authenticator) {
  122.             // recheck if the authenticator still supports the listener. supports() is called
  123.             // eagerly (before token storage is initialized), whereas authenticate() is called
  124.             // lazily (after initialization).
  125.             if (false === $authenticator->supports($request)) {
  126.                 if (null !== $this->logger) {
  127.                     $this->logger->debug('Skipping the "{authenticator}" authenticator as it did not support the request.', ['authenticator' => \get_class($authenticator)]);
  128.                 }
  129.                 continue;
  130.             }
  131.             $response $this->executeAuthenticator($authenticator$request);
  132.             if (null !== $response) {
  133.                 if (null !== $this->logger) {
  134.                     $this->logger->debug('The "{authenticator}" authenticator set the response. Any later authenticator will not be called', ['authenticator' => \get_class($authenticator)]);
  135.                 }
  136.                 return $response;
  137.             }
  138.         }
  139.         return null;
  140.     }
  141.     private function executeAuthenticator(AuthenticatorInterface $authenticatorRequest $request): ?Response
  142.     {
  143.         $passport null;
  144.         try {
  145.             // get the passport from the Authenticator
  146.             $passport $authenticator->authenticate($request);
  147.             // check the passport (e.g. password checking)
  148.             $event = new CheckPassportEvent($authenticator$passport);
  149.             $this->eventDispatcher->dispatch($event);
  150.             // check if all badges are resolved
  151.             $resolvedBadges = [];
  152.             foreach ($passport->getBadges() as $badge) {
  153.                 if (!$badge->isResolved()) {
  154.                     throw new BadCredentialsException(sprintf('Authentication failed: Security badge "%s" is not resolved, did you forget to register the correct listeners?'get_debug_type($badge)));
  155.                 }
  156.                 $resolvedBadges[] = \get_class($badge);
  157.             }
  158.             $missingRequiredBadges array_diff($this->requiredBadges$resolvedBadges);
  159.             if ($missingRequiredBadges) {
  160.                 throw new BadCredentialsException(sprintf('Authentication failed; Some badges marked as required by the firewall config are not available on the passport: "%s".'implode('", "'$missingRequiredBadges)));
  161.             }
  162.             // create the authenticated token
  163.             $authenticatedToken $authenticator->createAuthenticatedToken($passport$this->firewallName);
  164.             // announce the authenticated token
  165.             $authenticatedToken $this->eventDispatcher->dispatch(new AuthenticationTokenCreatedEvent($authenticatedToken$passport))->getAuthenticatedToken();
  166.             if (true === $this->eraseCredentials) {
  167.                 $authenticatedToken->eraseCredentials();
  168.             }
  169.             $this->eventDispatcher->dispatch(new AuthenticationSuccessEvent($authenticatedToken), AuthenticationEvents::AUTHENTICATION_SUCCESS);
  170.             if (null !== $this->logger) {
  171.                 $this->logger->info('Authenticator successful!', ['token' => $authenticatedToken'authenticator' => \get_class($authenticator)]);
  172.             }
  173.         } catch (AuthenticationException $e) {
  174.             // oh no! Authentication failed!
  175.             $response $this->handleAuthenticationFailure($e$request$authenticator$passport);
  176.             if ($response instanceof Response) {
  177.                 return $response;
  178.             }
  179.             return null;
  180.         }
  181.         // success! (sets the token on the token storage, etc)
  182.         $response $this->handleAuthenticationSuccess($authenticatedToken$passport$request$authenticator);
  183.         if ($response instanceof Response) {
  184.             return $response;
  185.         }
  186.         if (null !== $this->logger) {
  187.             $this->logger->debug('Authenticator set no success response: request continues.', ['authenticator' => \get_class($authenticator)]);
  188.         }
  189.         return null;
  190.     }
  191.     private function handleAuthenticationSuccess(TokenInterface $authenticatedTokenPassportInterface $passportRequest $requestAuthenticatorInterface $authenticator): ?Response
  192.     {
  193.         // @deprecated since Symfony 5.3
  194.         $user $authenticatedToken->getUser();
  195.         if ($user instanceof UserInterface && !method_exists($user'getUserIdentifier')) {
  196.             trigger_deprecation('symfony/security-core''5.3''Not implementing method "getUserIdentifier(): string" in user class "%s" is deprecated. This method will replace "getUsername()" in Symfony 6.0.'get_debug_type($authenticatedToken->getUser()));
  197.         }
  198.         $this->tokenStorage->setToken($authenticatedToken);
  199.         $response $authenticator->onAuthenticationSuccess($request$authenticatedToken$this->firewallName);
  200.         if ($authenticator instanceof InteractiveAuthenticatorInterface && $authenticator->isInteractive()) {
  201.             $loginEvent = new InteractiveLoginEvent($request$authenticatedToken);
  202.             $this->eventDispatcher->dispatch($loginEventSecurityEvents::INTERACTIVE_LOGIN);
  203.         }
  204.         $this->eventDispatcher->dispatch($loginSuccessEvent = new LoginSuccessEvent($authenticator$passport$authenticatedToken$request$response$this->firewallName));
  205.         return $loginSuccessEvent->getResponse();
  206.     }
  207.     /**
  208.      * Handles an authentication failure and returns the Response for the authenticator.
  209.      */
  210.     private function handleAuthenticationFailure(AuthenticationException $authenticationExceptionRequest $requestAuthenticatorInterface $authenticator, ?PassportInterface $passport): ?Response
  211.     {
  212.         if (null !== $this->logger) {
  213.             $this->logger->info('Authenticator failed.', ['exception' => $authenticationException'authenticator' => \get_class($authenticator)]);
  214.         }
  215.         // Avoid leaking error details in case of invalid user (e.g. user not found or invalid account status)
  216.         // to prevent user enumeration via response content comparison
  217.         if ($this->hideUserNotFoundExceptions && ($authenticationException instanceof UsernameNotFoundException || ($authenticationException instanceof AccountStatusException && !$authenticationException instanceof CustomUserMessageAccountStatusException))) {
  218.             $authenticationException = new BadCredentialsException('Bad credentials.'0$authenticationException);
  219.         }
  220.         $response $authenticator->onAuthenticationFailure($request$authenticationException);
  221.         if (null !== $response && null !== $this->logger) {
  222.             $this->logger->debug('The "{authenticator}" authenticator set the failure response.', ['authenticator' => \get_class($authenticator)]);
  223.         }
  224.         $this->eventDispatcher->dispatch($loginFailureEvent = new LoginFailureEvent($authenticationException$authenticator$request$response$this->firewallName$passport));
  225.         // returning null is ok, it means they want the request to continue
  226.         return $loginFailureEvent->getResponse();
  227.     }
  228. }