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

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