vendor/symfony/security-guard/Firewall/GuardAuthenticationListener.php line 39

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