vendor/symfony/security-guard/Firewall/GuardAuthenticationListener.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\Guard\Firewall;
  11. use Psr\Log\LoggerInterface;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\HttpFoundation\Response;
  14. use Symfony\Component\HttpKernel\Event\RequestEvent;
  15. use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
  16. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  17. use Symfony\Component\Security\Core\Exception\AccountStatusException;
  18. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  19. use Symfony\Component\Security\Core\Exception\BadCredentialsException;
  20. use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
  21. use Symfony\Component\Security\Guard\AuthenticatorInterface;
  22. use Symfony\Component\Security\Guard\GuardAuthenticatorHandler;
  23. use Symfony\Component\Security\Guard\Token\PreAuthenticationGuardToken;
  24. use Symfony\Component\Security\Http\Firewall\AbstractListener;
  25. use Symfony\Component\Security\Http\Firewall\LegacyListenerTrait;
  26. use Symfony\Component\Security\Http\Firewall\ListenerInterface;
  27. use Symfony\Component\Security\Http\RememberMe\RememberMeServicesInterface;
  28. /**
  29.  * Authentication listener for the "guard" system.
  30.  *
  31.  * @author Ryan Weaver <ryan@knpuniversity.com>
  32.  * @author Amaury Leroux de Lens <amaury@lerouxdelens.com>
  33.  *
  34.  * @final since Symfony 4.3
  35.  */
  36. class GuardAuthenticationListener extends AbstractListener implements ListenerInterface
  37. {
  38.     use LegacyListenerTrait;
  39.     private $guardHandler;
  40.     private $authenticationManager;
  41.     private $providerKey;
  42.     private $guardAuthenticators;
  43.     private $logger;
  44.     private $rememberMeServices;
  45.     private $hideUserNotFoundExceptions;
  46.     /**
  47.      * @param string                            $providerKey         The provider (i.e. firewall) key
  48.      * @param iterable|AuthenticatorInterface[] $guardAuthenticators The authenticators, with keys that match what's passed to GuardAuthenticationProvider
  49.      */
  50.     public function __construct(GuardAuthenticatorHandler $guardHandlerAuthenticationManagerInterface $authenticationManagerstring $providerKeyiterable $guardAuthenticatorsLoggerInterface $logger nullbool $hideUserNotFoundExceptions true)
  51.     {
  52.         if (empty($providerKey)) {
  53.             throw new \InvalidArgumentException('$providerKey must not be empty.');
  54.         }
  55.         $this->guardHandler $guardHandler;
  56.         $this->authenticationManager $authenticationManager;
  57.         $this->providerKey $providerKey;
  58.         $this->guardAuthenticators $guardAuthenticators;
  59.         $this->logger $logger;
  60.         $this->hideUserNotFoundExceptions $hideUserNotFoundExceptions;
  61.     }
  62.     /**
  63.      * {@inheritdoc}
  64.      */
  65.     public function supports(Request $request): ?bool
  66.     {
  67.         if (null !== $this->logger) {
  68.             $context = ['firewall_key' => $this->providerKey];
  69.             if ($this->guardAuthenticators instanceof \Countable || \is_array($this->guardAuthenticators)) {
  70.                 $context['authenticators'] = \count($this->guardAuthenticators);
  71.             }
  72.             $this->logger->debug('Checking for guard authentication credentials.'$context);
  73.         }
  74.         $guardAuthenticators = [];
  75.         foreach ($this->guardAuthenticators as $key => $guardAuthenticator) {
  76.             if (null !== $this->logger) {
  77.                 $this->logger->debug('Checking support on guard authenticator.', ['firewall_key' => $this->providerKey'authenticator' => \get_class($guardAuthenticator)]);
  78.             }
  79.             if ($guardAuthenticator->supports($request)) {
  80.                 $guardAuthenticators[$key] = $guardAuthenticator;
  81.             } elseif (null !== $this->logger) {
  82.                 $this->logger->debug('Guard authenticator does not support the request.', ['firewall_key' => $this->providerKey'authenticator' => \get_class($guardAuthenticator)]);
  83.             }
  84.         }
  85.         if (!$guardAuthenticators) {
  86.             return false;
  87.         }
  88.         $request->attributes->set('_guard_authenticators'$guardAuthenticators);
  89.         return true;
  90.     }
  91.     /**
  92.      * Iterates over each authenticator to see if each wants to authenticate the request.
  93.      */
  94.     public function authenticate(RequestEvent $event)
  95.     {
  96.         $request $event->getRequest();
  97.         $guardAuthenticators $request->attributes->get('_guard_authenticators');
  98.         $request->attributes->remove('_guard_authenticators');
  99.         foreach ($guardAuthenticators as $key => $guardAuthenticator) {
  100.             // get a key that's unique to *this* guard authenticator
  101.             // this MUST be the same as GuardAuthenticationProvider
  102.             $uniqueGuardKey $this->providerKey.'_'.$key;
  103.             $this->executeGuardAuthenticator($uniqueGuardKey$guardAuthenticator$event);
  104.             if ($event->hasResponse()) {
  105.                 if (null !== $this->logger) {
  106.                     $this->logger->debug('The "{authenticator}" authenticator set the response. Any later authenticator will not be called', ['authenticator' => \get_class($guardAuthenticator)]);
  107.                 }
  108.                 break;
  109.             }
  110.         }
  111.     }
  112.     private function executeGuardAuthenticator(string $uniqueGuardKeyAuthenticatorInterface $guardAuthenticatorRequestEvent $event)
  113.     {
  114.         $request $event->getRequest();
  115.         try {
  116.             if (null !== $this->logger) {
  117.                 $this->logger->debug('Calling getCredentials() on guard authenticator.', ['firewall_key' => $this->providerKey'authenticator' => \get_class($guardAuthenticator)]);
  118.             }
  119.             // allow the authenticator to fetch authentication info from the request
  120.             $credentials $guardAuthenticator->getCredentials($request);
  121.             if (null === $credentials) {
  122.                 throw new \UnexpectedValueException(sprintf('The return value of "%1$s::getCredentials()" must not be null. Return false from "%1$s::supports()" instead.', \get_class($guardAuthenticator)));
  123.             }
  124.             // create a token with the unique key, so that the provider knows which authenticator to use
  125.             $token = new PreAuthenticationGuardToken($credentials$uniqueGuardKey);
  126.             if (null !== $this->logger) {
  127.                 $this->logger->debug('Passing guard token information to the GuardAuthenticationProvider', ['firewall_key' => $this->providerKey'authenticator' => \get_class($guardAuthenticator)]);
  128.             }
  129.             // pass the token into the AuthenticationManager system
  130.             // this indirectly calls GuardAuthenticationProvider::authenticate()
  131.             $token $this->authenticationManager->authenticate($token);
  132.             if (null !== $this->logger) {
  133.                 $this->logger->info('Guard authentication successful!', ['token' => $token'authenticator' => \get_class($guardAuthenticator)]);
  134.             }
  135.             // sets the token on the token storage, etc
  136.             $this->guardHandler->authenticateWithToken($token$request$this->providerKey);
  137.         } catch (AuthenticationException $e) {
  138.             // oh no! Authentication failed!
  139.             if (null !== $this->logger) {
  140.                 $this->logger->info('Guard authentication failed.', ['exception' => $e'authenticator' => \get_class($guardAuthenticator)]);
  141.             }
  142.             // Avoid leaking error details in case of invalid user (e.g. user not found or invalid account status)
  143.             // to prevent user enumeration via response content
  144.             if ($this->hideUserNotFoundExceptions && ($e instanceof UsernameNotFoundException || $e instanceof AccountStatusException)) {
  145.                 $e = new BadCredentialsException('Bad credentials.'0$e);
  146.             }
  147.             $response $this->guardHandler->handleAuthenticationFailure($e$request$guardAuthenticator$this->providerKey);
  148.             if ($response instanceof Response) {
  149.                 $event->setResponse($response);
  150.             }
  151.             return;
  152.         }
  153.         // success!
  154.         $response $this->guardHandler->handleAuthenticationSuccess($token$request$guardAuthenticator$this->providerKey);
  155.         if ($response instanceof Response) {
  156.             if (null !== $this->logger) {
  157.                 $this->logger->debug('Guard authenticator set success response.', ['response' => $response'authenticator' => \get_class($guardAuthenticator)]);
  158.             }
  159.             $event->setResponse($response);
  160.         } else {
  161.             if (null !== $this->logger) {
  162.                 $this->logger->debug('Guard authenticator set no success response: request continues.', ['authenticator' => \get_class($guardAuthenticator)]);
  163.             }
  164.         }
  165.         // attempt to trigger the remember me functionality
  166.         $this->triggerRememberMe($guardAuthenticator$request$token$response);
  167.     }
  168.     /**
  169.      * Should be called if this listener will support remember me.
  170.      */
  171.     public function setRememberMeServices(RememberMeServicesInterface $rememberMeServices)
  172.     {
  173.         $this->rememberMeServices $rememberMeServices;
  174.     }
  175.     /**
  176.      * Checks to see if remember me is supported in the authenticator and
  177.      * on the firewall. If it is, the RememberMeServicesInterface is notified.
  178.      */
  179.     private function triggerRememberMe(AuthenticatorInterface $guardAuthenticatorRequest $requestTokenInterface $tokenResponse $response null)
  180.     {
  181.         if (null === $this->rememberMeServices) {
  182.             if (null !== $this->logger) {
  183.                 $this->logger->debug('Remember me skipped: it is not configured for the firewall.', ['authenticator' => \get_class($guardAuthenticator)]);
  184.             }
  185.             return;
  186.         }
  187.         if (!$guardAuthenticator->supportsRememberMe()) {
  188.             if (null !== $this->logger) {
  189.                 $this->logger->debug('Remember me skipped: your authenticator does not support it.', ['authenticator' => \get_class($guardAuthenticator)]);
  190.             }
  191.             return;
  192.         }
  193.         if (!$response instanceof Response) {
  194.             throw new \LogicException(sprintf('"%s::onAuthenticationSuccess()" *must* return a Response if you want to use the remember me functionality. Return a Response, or set remember_me to false under the guard configuration.', \get_class($guardAuthenticator)));
  195.         }
  196.         $this->rememberMeServices->loginSuccess($request$response$token);
  197.     }
  198. }