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

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