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