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

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