vendor/symfony/security-http/Firewall/AbstractAuthenticationListener.php line 128

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\Http\Firewall;
  11. use Psr\Log\LoggerInterface;
  12. use Symfony\Component\EventDispatcher\LegacyEventDispatcherProxy;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpFoundation\Response;
  15. use Symfony\Component\HttpKernel\Event\RequestEvent;
  16. use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
  17. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  18. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  19. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  20. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  21. use Symfony\Component\Security\Core\Exception\SessionUnavailableException;
  22. use Symfony\Component\Security\Core\Security;
  23. use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
  24. use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
  25. use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
  26. use Symfony\Component\Security\Http\HttpUtils;
  27. use Symfony\Component\Security\Http\RememberMe\RememberMeServicesInterface;
  28. use Symfony\Component\Security\Http\SecurityEvents;
  29. use Symfony\Component\Security\Http\Session\SessionAuthenticationStrategyInterface;
  30. use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
  31. /**
  32.  * The AbstractAuthenticationListener is the preferred base class for all
  33.  * browser-/HTTP-based authentication requests.
  34.  *
  35.  * Subclasses likely have to implement the following:
  36.  * - an TokenInterface to hold authentication related data
  37.  * - an AuthenticationProvider to perform the actual authentication of the
  38.  *   token, retrieve the UserInterface implementation from a database, and
  39.  *   perform the specific account checks using the UserChecker
  40.  *
  41.  * By default, this listener only is active for a specific path, e.g.
  42.  * /login_check. If you want to change this behavior, you can overwrite the
  43.  * requiresAuthentication() method.
  44.  *
  45.  * @author Fabien Potencier <fabien@symfony.com>
  46.  * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  47.  */
  48. abstract class AbstractAuthenticationListener extends AbstractListener implements ListenerInterface
  49. {
  50.     use LegacyListenerTrait;
  51.     protected $options;
  52.     protected $logger;
  53.     protected $authenticationManager;
  54.     protected $providerKey;
  55.     protected $httpUtils;
  56.     private $tokenStorage;
  57.     private $sessionStrategy;
  58.     private $dispatcher;
  59.     private $successHandler;
  60.     private $failureHandler;
  61.     private $rememberMeServices;
  62.     /**
  63.      * @throws \InvalidArgumentException
  64.      */
  65.     public function __construct(TokenStorageInterface $tokenStorageAuthenticationManagerInterface $authenticationManagerSessionAuthenticationStrategyInterface $sessionStrategyHttpUtils $httpUtilsstring $providerKeyAuthenticationSuccessHandlerInterface $successHandlerAuthenticationFailureHandlerInterface $failureHandler, array $options = [], LoggerInterface $logger nullEventDispatcherInterface $dispatcher null)
  66.     {
  67.         if (empty($providerKey)) {
  68.             throw new \InvalidArgumentException('$providerKey must not be empty.');
  69.         }
  70.         $this->tokenStorage $tokenStorage;
  71.         $this->authenticationManager $authenticationManager;
  72.         $this->sessionStrategy $sessionStrategy;
  73.         $this->providerKey $providerKey;
  74.         $this->successHandler $successHandler;
  75.         $this->failureHandler $failureHandler;
  76.         $this->options array_merge([
  77.             'check_path' => '/login_check',
  78.             'login_path' => '/login',
  79.             'always_use_default_target_path' => false,
  80.             'default_target_path' => '/',
  81.             'target_path_parameter' => '_target_path',
  82.             'use_referer' => false,
  83.             'failure_path' => null,
  84.             'failure_forward' => false,
  85.             'require_previous_session' => true,
  86.         ], $options);
  87.         $this->logger $logger;
  88.         if (null !== $dispatcher && class_exists(LegacyEventDispatcherProxy::class)) {
  89.             $this->dispatcher LegacyEventDispatcherProxy::decorate($dispatcher);
  90.         } else {
  91.             $this->dispatcher $dispatcher;
  92.         }
  93.         $this->httpUtils $httpUtils;
  94.     }
  95.     /**
  96.      * Sets the RememberMeServices implementation to use.
  97.      */
  98.     public function setRememberMeServices(RememberMeServicesInterface $rememberMeServices)
  99.     {
  100.         $this->rememberMeServices $rememberMeServices;
  101.     }
  102.     /**
  103.      * {@inheritdoc}
  104.      */
  105.     public function supports(Request $request): ?bool
  106.     {
  107.         return $this->requiresAuthentication($request);
  108.     }
  109.     /**
  110.      * Handles form based authentication.
  111.      *
  112.      * @throws \RuntimeException
  113.      * @throws SessionUnavailableException
  114.      */
  115.     public function authenticate(RequestEvent $event)
  116.     {
  117.         $request $event->getRequest();
  118.         if (!$request->hasSession()) {
  119.             throw new \RuntimeException('This authentication method requires a session.');
  120.         }
  121.         try {
  122.             if ($this->options['require_previous_session'] && !$request->hasPreviousSession()) {
  123.                 throw new SessionUnavailableException('Your session has timed out, or you have disabled cookies.');
  124.             }
  125.             if (null === $returnValue $this->attemptAuthentication($request)) {
  126.                 return;
  127.             }
  128.             if ($returnValue instanceof TokenInterface) {
  129.                 $this->sessionStrategy->onAuthentication($request$returnValue);
  130.                 $response $this->onSuccess($request$returnValue);
  131.             } elseif ($returnValue instanceof Response) {
  132.                 $response $returnValue;
  133.             } else {
  134.                 throw new \RuntimeException('attemptAuthentication() must either return a Response, an implementation of TokenInterface, or null.');
  135.             }
  136.         } catch (AuthenticationException $e) {
  137.             $response $this->onFailure($request$e);
  138.         }
  139.         $event->setResponse($response);
  140.     }
  141.     /**
  142.      * Whether this request requires authentication.
  143.      *
  144.      * The default implementation only processes requests to a specific path,
  145.      * but a subclass could change this to only authenticate requests where a
  146.      * certain parameters is present.
  147.      *
  148.      * @return bool
  149.      */
  150.     protected function requiresAuthentication(Request $request)
  151.     {
  152.         return $this->httpUtils->checkRequestPath($request$this->options['check_path']);
  153.     }
  154.     /**
  155.      * Performs authentication.
  156.      *
  157.      * @return TokenInterface|Response|null The authenticated token, null if full authentication is not possible, or a Response
  158.      *
  159.      * @throws AuthenticationException if the authentication fails
  160.      */
  161.     abstract protected function attemptAuthentication(Request $request);
  162.     private function onFailure(Request $requestAuthenticationException $failed): Response
  163.     {
  164.         if (null !== $this->logger) {
  165.             $this->logger->info('Authentication request failed.', ['exception' => $failed]);
  166.         }
  167.         $token $this->tokenStorage->getToken();
  168.         if ($token instanceof UsernamePasswordToken && $this->providerKey === $token->getProviderKey()) {
  169.             $this->tokenStorage->setToken(null);
  170.         }
  171.         $response $this->failureHandler->onAuthenticationFailure($request$failed);
  172.         if (!$response instanceof Response) {
  173.             throw new \RuntimeException('Authentication Failure Handler did not return a Response.');
  174.         }
  175.         return $response;
  176.     }
  177.     private function onSuccess(Request $requestTokenInterface $token): Response
  178.     {
  179.         if (null !== $this->logger) {
  180.             $this->logger->info('User has been authenticated successfully.', ['username' => $token->getUsername()]);
  181.         }
  182.         $this->tokenStorage->setToken($token);
  183.         $session $request->getSession();
  184.         $session->remove(Security::AUTHENTICATION_ERROR);
  185.         $session->remove(Security::LAST_USERNAME);
  186.         if (null !== $this->dispatcher) {
  187.             $loginEvent = new InteractiveLoginEvent($request$token);
  188.             $this->dispatcher->dispatch($loginEventSecurityEvents::INTERACTIVE_LOGIN);
  189.         }
  190.         $response $this->successHandler->onAuthenticationSuccess($request$token);
  191.         if (!$response instanceof Response) {
  192.             throw new \RuntimeException('Authentication Success Handler did not return a Response.');
  193.         }
  194.         if (null !== $this->rememberMeServices) {
  195.             $this->rememberMeServices->loginSuccess($request$response$token);
  196.         }
  197.         return $response;
  198.     }
  199. }