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