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

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.  * @experimental in 5.2
  43.  */
  44. class AuthenticatorManager implements AuthenticatorManagerInterfaceUserAuthenticatorInterface
  45. {
  46.     private $authenticators;
  47.     private $tokenStorage;
  48.     private $eventDispatcher;
  49.     private $eraseCredentials;
  50.     private $logger;
  51.     private $firewallName;
  52.     private $hideUserNotFoundExceptions;
  53.     /**
  54.      * @param AuthenticatorInterface[] $authenticators
  55.      */
  56.     public function __construct(iterable $authenticatorsTokenStorageInterface $tokenStorageEventDispatcherInterface $eventDispatcherstring $firewallNameLoggerInterface $logger nullbool $eraseCredentials truebool $hideUserNotFoundExceptions true)
  57.     {
  58.         $this->authenticators $authenticators;
  59.         $this->tokenStorage $tokenStorage;
  60.         $this->eventDispatcher $eventDispatcher;
  61.         $this->firewallName $firewallName;
  62.         $this->logger $logger;
  63.         $this->eraseCredentials $eraseCredentials;
  64.         $this->hideUserNotFoundExceptions $hideUserNotFoundExceptions;
  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.         $token $authenticator->createAuthenticatedToken($passport = new SelfValidatingPassport(new UserBadge($user->getUsername(), function () use ($user) { return $user; }), $badges), $this->firewallName);
  73.         // announce the authenticated token
  74.         $token $this->eventDispatcher->dispatch(new AuthenticationTokenCreatedEvent($token))->getAuthenticatedToken();
  75.         // authenticate this in the system
  76.         return $this->handleAuthenticationSuccess($token$passport$request$authenticator);
  77.     }
  78.     public function supports(Request $request): ?bool
  79.     {
  80.         if (null !== $this->logger) {
  81.             $context = ['firewall_name' => $this->firewallName];
  82.             if ($this->authenticators instanceof \Countable || \is_array($this->authenticators)) {
  83.                 $context['authenticators'] = \count($this->authenticators);
  84.             }
  85.             $this->logger->debug('Checking for authenticator support.'$context);
  86.         }
  87.         $authenticators = [];
  88.         $lazy true;
  89.         foreach ($this->authenticators as $authenticator) {
  90.             if (null !== $this->logger) {
  91.                 $this->logger->debug('Checking support on authenticator.', ['firewall_name' => $this->firewallName'authenticator' => \get_class($authenticator)]);
  92.             }
  93.             if (false !== $supports $authenticator->supports($request)) {
  94.                 $authenticators[] = $authenticator;
  95.                 $lazy $lazy && null === $supports;
  96.             } elseif (null !== $this->logger) {
  97.                 $this->logger->debug('Authenticator does not support the request.', ['firewall_name' => $this->firewallName'authenticator' => \get_class($authenticator)]);
  98.             }
  99.         }
  100.         if (!$authenticators) {
  101.             return false;
  102.         }
  103.         $request->attributes->set('_security_authenticators'$authenticators);
  104.         return $lazy null true;
  105.     }
  106.     public function authenticateRequest(Request $request): ?Response
  107.     {
  108.         $authenticators $request->attributes->get('_security_authenticators');
  109.         $request->attributes->remove('_security_authenticators');
  110.         if (!$authenticators) {
  111.             return null;
  112.         }
  113.         return $this->executeAuthenticators($authenticators$request);
  114.     }
  115.     /**
  116.      * @param AuthenticatorInterface[] $authenticators
  117.      */
  118.     private function executeAuthenticators(array $authenticatorsRequest $request): ?Response
  119.     {
  120.         foreach ($authenticators as $authenticator) {
  121.             // recheck if the authenticator still supports the listener. supports() is called
  122.             // eagerly (before token storage is initialized), whereas authenticate() is called
  123.             // lazily (after initialization).
  124.             if (false === $authenticator->supports($request)) {
  125.                 if (null !== $this->logger) {
  126.                     $this->logger->debug('Skipping the "{authenticator}" authenticator as it did not support the request.', ['authenticator' => \get_class($authenticator)]);
  127.                 }
  128.                 continue;
  129.             }
  130.             $response $this->executeAuthenticator($authenticator$request);
  131.             if (null !== $response) {
  132.                 if (null !== $this->logger) {
  133.                     $this->logger->debug('The "{authenticator}" authenticator set the response. Any later authenticator will not be called', ['authenticator' => \get_class($authenticator)]);
  134.                 }
  135.                 return $response;
  136.             }
  137.         }
  138.         return null;
  139.     }
  140.     private function executeAuthenticator(AuthenticatorInterface $authenticatorRequest $request): ?Response
  141.     {
  142.         $passport null;
  143.         try {
  144.             // get the passport from the Authenticator
  145.             $passport $authenticator->authenticate($request);
  146.             // check the passport (e.g. password checking)
  147.             $event = new CheckPassportEvent($authenticator$passport);
  148.             $this->eventDispatcher->dispatch($event);
  149.             // check if all badges are resolved
  150.             $passport->checkIfCompletelyResolved();
  151.             // create the authenticated token
  152.             $authenticatedToken $authenticator->createAuthenticatedToken($passport$this->firewallName);
  153.             // announce the authenticated token
  154.             $authenticatedToken $this->eventDispatcher->dispatch(new AuthenticationTokenCreatedEvent($authenticatedToken))->getAuthenticatedToken();
  155.             if (true === $this->eraseCredentials) {
  156.                 $authenticatedToken->eraseCredentials();
  157.             }
  158.             $this->eventDispatcher->dispatch(new AuthenticationSuccessEvent($authenticatedToken), AuthenticationEvents::AUTHENTICATION_SUCCESS);
  159.             if (null !== $this->logger) {
  160.                 $this->logger->info('Authenticator successful!', ['token' => $authenticatedToken'authenticator' => \get_class($authenticator)]);
  161.             }
  162.         } catch (AuthenticationException $e) {
  163.             // oh no! Authentication failed!
  164.             $response $this->handleAuthenticationFailure($e$request$authenticator$passport);
  165.             if ($response instanceof Response) {
  166.                 return $response;
  167.             }
  168.             return null;
  169.         }
  170.         // success! (sets the token on the token storage, etc)
  171.         $response $this->handleAuthenticationSuccess($authenticatedToken$passport$request$authenticator);
  172.         if ($response instanceof Response) {
  173.             return $response;
  174.         }
  175.         if (null !== $this->logger) {
  176.             $this->logger->debug('Authenticator set no success response: request continues.', ['authenticator' => \get_class($authenticator)]);
  177.         }
  178.         return null;
  179.     }
  180.     private function handleAuthenticationSuccess(TokenInterface $authenticatedTokenPassportInterface $passportRequest $requestAuthenticatorInterface $authenticator): ?Response
  181.     {
  182.         $this->tokenStorage->setToken($authenticatedToken);
  183.         $response $authenticator->onAuthenticationSuccess($request$authenticatedToken$this->firewallName);
  184.         if ($authenticator instanceof InteractiveAuthenticatorInterface && $authenticator->isInteractive()) {
  185.             $loginEvent = new InteractiveLoginEvent($request$authenticatedToken);
  186.             $this->eventDispatcher->dispatch($loginEventSecurityEvents::INTERACTIVE_LOGIN);
  187.         }
  188.         $this->eventDispatcher->dispatch($loginSuccessEvent = new LoginSuccessEvent($authenticator$passport$authenticatedToken$request$response$this->firewallName));
  189.         return $loginSuccessEvent->getResponse();
  190.     }
  191.     /**
  192.      * Handles an authentication failure and returns the Response for the authenticator.
  193.      */
  194.     private function handleAuthenticationFailure(AuthenticationException $authenticationExceptionRequest $requestAuthenticatorInterface $authenticator, ?PassportInterface $passport): ?Response
  195.     {
  196.         if (null !== $this->logger) {
  197.             $this->logger->info('Authenticator failed.', ['exception' => $authenticationException'authenticator' => \get_class($authenticator)]);
  198.         }
  199.         // Avoid leaking error details in case of invalid user (e.g. user not found or invalid account status)
  200.         // to prevent user enumeration via response content comparison
  201.         if ($this->hideUserNotFoundExceptions && ($authenticationException instanceof UsernameNotFoundException || ($authenticationException instanceof AccountStatusException && !$authenticationException instanceof CustomUserMessageAccountStatusException))) {
  202.             $authenticationException = new BadCredentialsException('Bad credentials.'0$authenticationException);
  203.         }
  204.         $response $authenticator->onAuthenticationFailure($request$authenticationException);
  205.         if (null !== $response && null !== $this->logger) {
  206.             $this->logger->debug('The "{authenticator}" authenticator set the failure response.', ['authenticator' => \get_class($authenticator)]);
  207.         }
  208.         $this->eventDispatcher->dispatch($loginFailureEvent = new LoginFailureEvent($authenticationException$authenticator$request$response$this->firewallName$passport));
  209.         // returning null is ok, it means they want the request to continue
  210.         return $loginFailureEvent->getResponse();
  211.     }
  212. }