vendor/symfony/security/Http/Firewall/AbstractAuthenticationListener.php line 140

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\EventDispatcherInterface;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpFoundation\Response;
  15. use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  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. /**
  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 implements ListenerInterface
  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.      * @param TokenStorageInterface                  $tokenStorage          A TokenStorageInterface instance
  62.      * @param AuthenticationManagerInterface         $authenticationManager An AuthenticationManagerInterface instance
  63.      * @param SessionAuthenticationStrategyInterface $sessionStrategy
  64.      * @param HttpUtils                              $httpUtils             An HttpUtils instance
  65.      * @param string                                 $providerKey
  66.      * @param AuthenticationSuccessHandlerInterface  $successHandler
  67.      * @param AuthenticationFailureHandlerInterface  $failureHandler
  68.      * @param array                                  $options               An array of options for the processing of a
  69.      *                                                                      successful, or failed authentication attempt
  70.      * @param LoggerInterface|null                   $logger                A LoggerInterface instance
  71.      * @param EventDispatcherInterface|null          $dispatcher            An EventDispatcherInterface instance
  72.      *
  73.      * @throws \InvalidArgumentException
  74.      */
  75.     public function __construct(TokenStorageInterface $tokenStorageAuthenticationManagerInterface $authenticationManagerSessionAuthenticationStrategyInterface $sessionStrategyHttpUtils $httpUtils$providerKeyAuthenticationSuccessHandlerInterface $successHandlerAuthenticationFailureHandlerInterface $failureHandler, array $options = [], LoggerInterface $logger nullEventDispatcherInterface $dispatcher null)
  76.     {
  77.         if (empty($providerKey)) {
  78.             throw new \InvalidArgumentException('$providerKey must not be empty.');
  79.         }
  80.         $this->tokenStorage $tokenStorage;
  81.         $this->authenticationManager $authenticationManager;
  82.         $this->sessionStrategy $sessionStrategy;
  83.         $this->providerKey $providerKey;
  84.         $this->successHandler $successHandler;
  85.         $this->failureHandler $failureHandler;
  86.         $this->options array_merge([
  87.             'check_path' => '/login_check',
  88.             'login_path' => '/login',
  89.             'always_use_default_target_path' => false,
  90.             'default_target_path' => '/',
  91.             'target_path_parameter' => '_target_path',
  92.             'use_referer' => false,
  93.             'failure_path' => null,
  94.             'failure_forward' => false,
  95.             'require_previous_session' => true,
  96.         ], $options);
  97.         $this->logger $logger;
  98.         $this->dispatcher $dispatcher;
  99.         $this->httpUtils $httpUtils;
  100.     }
  101.     /**
  102.      * Sets the RememberMeServices implementation to use.
  103.      */
  104.     public function setRememberMeServices(RememberMeServicesInterface $rememberMeServices)
  105.     {
  106.         $this->rememberMeServices $rememberMeServices;
  107.     }
  108.     /**
  109.      * Handles form based authentication.
  110.      *
  111.      * @throws \RuntimeException
  112.      * @throws SessionUnavailableException
  113.      */
  114.     final public function handle(GetResponseEvent $event)
  115.     {
  116.         $request $event->getRequest();
  117.         if (!$this->requiresAuthentication($request)) {
  118.             return;
  119.         }
  120.         if (!$request->hasSession()) {
  121.             throw new \RuntimeException('This authentication method requires a session.');
  122.         }
  123.         try {
  124.             if ($this->options['require_previous_session'] && !$request->hasPreviousSession()) {
  125.                 throw new SessionUnavailableException('Your session has timed out, or you have disabled cookies.');
  126.             }
  127.             if (null === $returnValue $this->attemptAuthentication($request)) {
  128.                 return;
  129.             }
  130.             if ($returnValue instanceof TokenInterface) {
  131.                 $this->sessionStrategy->onAuthentication($request$returnValue);
  132.                 $response $this->onSuccess($request$returnValue);
  133.             } elseif ($returnValue instanceof Response) {
  134.                 $response $returnValue;
  135.             } else {
  136.                 throw new \RuntimeException('attemptAuthentication() must either return a Response, an implementation of TokenInterface, or null.');
  137.             }
  138.         } catch (AuthenticationException $e) {
  139.             $response $this->onFailure($request$e);
  140.         }
  141.         $event->setResponse($response);
  142.     }
  143.     /**
  144.      * Whether this request requires authentication.
  145.      *
  146.      * The default implementation only processes requests to a specific path,
  147.      * but a subclass could change this to only authenticate requests where a
  148.      * certain parameters is present.
  149.      *
  150.      * @return bool
  151.      */
  152.     protected function requiresAuthentication(Request $request)
  153.     {
  154.         return $this->httpUtils->checkRequestPath($request$this->options['check_path']);
  155.     }
  156.     /**
  157.      * Performs authentication.
  158.      *
  159.      * @return TokenInterface|Response|null The authenticated token, null if full authentication is not possible, or a Response
  160.      *
  161.      * @throws AuthenticationException if the authentication fails
  162.      */
  163.     abstract protected function attemptAuthentication(Request $request);
  164.     private function onFailure(Request $requestAuthenticationException $failed)
  165.     {
  166.         if (null !== $this->logger) {
  167.             $this->logger->info('Authentication request failed.', ['exception' => $failed]);
  168.         }
  169.         $token $this->tokenStorage->getToken();
  170.         if ($token instanceof UsernamePasswordToken && $this->providerKey === $token->getProviderKey()) {
  171.             $this->tokenStorage->setToken(null);
  172.         }
  173.         $response $this->failureHandler->onAuthenticationFailure($request$failed);
  174.         if (!$response instanceof Response) {
  175.             throw new \RuntimeException('Authentication Failure Handler did not return a Response.');
  176.         }
  177.         return $response;
  178.     }
  179.     private function onSuccess(Request $requestTokenInterface $token)
  180.     {
  181.         if (null !== $this->logger) {
  182.             $this->logger->info('User has been authenticated successfully.', ['username' => $token->getUsername()]);
  183.         }
  184.         $this->tokenStorage->setToken($token);
  185.         $session $request->getSession();
  186.         $session->remove(Security::AUTHENTICATION_ERROR);
  187.         $session->remove(Security::LAST_USERNAME);
  188.         if (null !== $this->dispatcher) {
  189.             $loginEvent = new InteractiveLoginEvent($request$token);
  190.             $this->dispatcher->dispatch(SecurityEvents::INTERACTIVE_LOGIN$loginEvent);
  191.         }
  192.         $response $this->successHandler->onAuthenticationSuccess($request$token);
  193.         if (!$response instanceof Response) {
  194.             throw new \RuntimeException('Authentication Success Handler did not return a Response.');
  195.         }
  196.         if (null !== $this->rememberMeServices) {
  197.             $this->rememberMeServices->loginSuccess($request$response$token);
  198.         }
  199.         return $response;
  200.     }
  201. }