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

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