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

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