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

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\Passport;
  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 iterable $authenticators;
  45.     private $tokenStorage;
  46.     private $eventDispatcher;
  47.     private bool $eraseCredentials;
  48.     private $logger;
  49.     private string $firewallName;
  50.     private bool $hideUserNotFoundExceptions;
  51.     private array $requiredBadges;
  52.     /**
  53.      * @param iterable<mixed, 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 authentication token for the User
  72.         $passport = new SelfValidatingPassport(new UserBadge($user->getUserIdentifier(), function () use ($user) { return $user; }), $badges);
  73.         $token $authenticator->createToken($passport$this->firewallName);
  74.         // announce the authentication 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.         $skippedAuthenticators = [];
  90.         $lazy true;
  91.         foreach ($this->authenticators as $authenticator) {
  92.             if (null !== $this->logger) {
  93.                 $this->logger->debug('Checking support on authenticator.', ['firewall_name' => $this->firewallName'authenticator' => \get_class($authenticator)]);
  94.             }
  95.             if (false !== $supports $authenticator->supports($request)) {
  96.                 $authenticators[] = $authenticator;
  97.                 $lazy $lazy && null === $supports;
  98.             } else {
  99.                 if (null !== $this->logger) {
  100.                     $this->logger->debug('Authenticator does not support the request.', ['firewall_name' => $this->firewallName'authenticator' => \get_class($authenticator)]);
  101.                 }
  102.                 $skippedAuthenticators[] = $authenticator;
  103.             }
  104.         }
  105.         if (!$authenticators) {
  106.             return false;
  107.         }
  108.         $request->attributes->set('_security_authenticators'$authenticators);
  109.         $request->attributes->set('_security_skipped_authenticators'$skippedAuthenticators);
  110.         return $lazy null true;
  111.     }
  112.     public function authenticateRequest(Request $request): ?Response
  113.     {
  114.         $authenticators $request->attributes->get('_security_authenticators');
  115.         $request->attributes->remove('_security_authenticators');
  116.         $request->attributes->remove('_security_skipped_authenticators');
  117.         if (!$authenticators) {
  118.             return null;
  119.         }
  120.         return $this->executeAuthenticators($authenticators$request);
  121.     }
  122.     /**
  123.      * @param AuthenticatorInterface[] $authenticators
  124.      */
  125.     private function executeAuthenticators(array $authenticatorsRequest $request): ?Response
  126.     {
  127.         foreach ($authenticators as $authenticator) {
  128.             // recheck if the authenticator still supports the listener. supports() is called
  129.             // eagerly (before token storage is initialized), whereas authenticate() is called
  130.             // lazily (after initialization).
  131.             if (false === $authenticator->supports($request)) {
  132.                 if (null !== $this->logger) {
  133.                     $this->logger->debug('Skipping the "{authenticator}" authenticator as it did not support the request.', ['authenticator' => \get_class($authenticator)]);
  134.                 }
  135.                 continue;
  136.             }
  137.             $response $this->executeAuthenticator($authenticator$request);
  138.             if (null !== $response) {
  139.                 if (null !== $this->logger) {
  140.                     $this->logger->debug('The "{authenticator}" authenticator set the response. Any later authenticator will not be called', ['authenticator' => \get_class($authenticator)]);
  141.                 }
  142.                 return $response;
  143.             }
  144.         }
  145.         return null;
  146.     }
  147.     private function executeAuthenticator(AuthenticatorInterface $authenticatorRequest $request): ?Response
  148.     {
  149.         $passport null;
  150.         try {
  151.             // get the passport from the Authenticator
  152.             $passport $authenticator->authenticate($request);
  153.             // check the passport (e.g. password checking)
  154.             $event = new CheckPassportEvent($authenticator$passport);
  155.             $this->eventDispatcher->dispatch($event);
  156.             // check if all badges are resolved
  157.             $resolvedBadges = [];
  158.             foreach ($passport->getBadges() as $badge) {
  159.                 if (!$badge->isResolved()) {
  160.                     throw new BadCredentialsException(sprintf('Authentication failed: Security badge "%s" is not resolved, did you forget to register the correct listeners?'get_debug_type($badge)));
  161.                 }
  162.                 $resolvedBadges[] = \get_class($badge);
  163.             }
  164.             $missingRequiredBadges array_diff($this->requiredBadges$resolvedBadges);
  165.             if ($missingRequiredBadges) {
  166.                 throw new BadCredentialsException(sprintf('Authentication failed; Some badges marked as required by the firewall config are not available on the passport: "%s".'implode('", "'$missingRequiredBadges)));
  167.             }
  168.             // create the authentication token
  169.             $authenticatedToken $authenticator->createToken($passport$this->firewallName);
  170.             // announce the authentication token
  171.             $authenticatedToken $this->eventDispatcher->dispatch(new AuthenticationTokenCreatedEvent($authenticatedToken$passport))->getAuthenticatedToken();
  172.             if (true === $this->eraseCredentials) {
  173.                 $authenticatedToken->eraseCredentials();
  174.             }
  175.             $this->eventDispatcher->dispatch(new AuthenticationSuccessEvent($authenticatedToken), AuthenticationEvents::AUTHENTICATION_SUCCESS);
  176.             if (null !== $this->logger) {
  177.                 $this->logger->info('Authenticator successful!', ['token' => $authenticatedToken'authenticator' => \get_class($authenticator)]);
  178.             }
  179.         } catch (AuthenticationException $e) {
  180.             // oh no! Authentication failed!
  181.             $response $this->handleAuthenticationFailure($e$request$authenticator$passport);
  182.             if ($response instanceof Response) {
  183.                 return $response;
  184.             }
  185.             return null;
  186.         }
  187.         // success! (sets the token on the token storage, etc)
  188.         $response $this->handleAuthenticationSuccess($authenticatedToken$passport$request$authenticator);
  189.         if ($response instanceof Response) {
  190.             return $response;
  191.         }
  192.         if (null !== $this->logger) {
  193.             $this->logger->debug('Authenticator set no success response: request continues.', ['authenticator' => \get_class($authenticator)]);
  194.         }
  195.         return null;
  196.     }
  197.     private function handleAuthenticationSuccess(TokenInterface $authenticatedTokenPassport $passportRequest $requestAuthenticatorInterface $authenticator): ?Response
  198.     {
  199.         $this->tokenStorage->setToken($authenticatedToken);
  200.         $response $authenticator->onAuthenticationSuccess($request$authenticatedToken$this->firewallName);
  201.         if ($authenticator instanceof InteractiveAuthenticatorInterface && $authenticator->isInteractive()) {
  202.             $loginEvent = new InteractiveLoginEvent($request$authenticatedToken);
  203.             $this->eventDispatcher->dispatch($loginEventSecurityEvents::INTERACTIVE_LOGIN);
  204.         }
  205.         $this->eventDispatcher->dispatch($loginSuccessEvent = new LoginSuccessEvent($authenticator$passport$authenticatedToken$request$response$this->firewallName));
  206.         return $loginSuccessEvent->getResponse();
  207.     }
  208.     /**
  209.      * Handles an authentication failure and returns the Response for the authenticator.
  210.      */
  211.     private function handleAuthenticationFailure(AuthenticationException $authenticationExceptionRequest $requestAuthenticatorInterface $authenticator, ?Passport $passport): ?Response
  212.     {
  213.         if (null !== $this->logger) {
  214.             $this->logger->info('Authenticator failed.', ['exception' => $authenticationException'authenticator' => \get_class($authenticator)]);
  215.         }
  216.         // Avoid leaking error details in case of invalid user (e.g. user not found or invalid account status)
  217.         // to prevent user enumeration via response content comparison
  218.         if ($this->hideUserNotFoundExceptions && ($authenticationException instanceof UsernameNotFoundException || ($authenticationException instanceof AccountStatusException && !$authenticationException instanceof CustomUserMessageAccountStatusException))) {
  219.             $authenticationException = new BadCredentialsException('Bad credentials.'0$authenticationException);
  220.         }
  221.         $response $authenticator->onAuthenticationFailure($request$authenticationException);
  222.         if (null !== $response && null !== $this->logger) {
  223.             $this->logger->debug('The "{authenticator}" authenticator set the failure response.', ['authenticator' => \get_class($authenticator)]);
  224.         }
  225.         $this->eventDispatcher->dispatch($loginFailureEvent = new LoginFailureEvent($authenticationException$authenticator$request$response$this->firewallName$passport));
  226.         // returning null is ok, it means they want the request to continue
  227.         return $loginFailureEvent->getResponse();
  228.     }
  229. }