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

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