vendor/symfony/security-http/Firewall/UsernamePasswordJsonAuthenticationListener.php line 47

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\JsonResponse;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\HttpFoundation\Response;
  16. use Symfony\Component\HttpKernel\Event\RequestEvent;
  17. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  18. use Symfony\Component\PropertyAccess\Exception\AccessException;
  19. use Symfony\Component\PropertyAccess\PropertyAccess;
  20. use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
  21. use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
  22. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  23. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  24. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  25. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  26. use Symfony\Component\Security\Core\Exception\BadCredentialsException;
  27. use Symfony\Component\Security\Core\Security;
  28. use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
  29. use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
  30. use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
  31. use Symfony\Component\Security\Http\HttpUtils;
  32. use Symfony\Component\Security\Http\SecurityEvents;
  33. use Symfony\Component\Security\Http\Session\SessionAuthenticationStrategyInterface;
  34. use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
  35. /**
  36.  * UsernamePasswordJsonAuthenticationListener is a stateless implementation of
  37.  * an authentication via a JSON document composed of a username and a password.
  38.  *
  39.  * @author Kévin Dunglas <dunglas@gmail.com>
  40.  *
  41.  * @final since Symfony 4.3
  42.  */
  43. class UsernamePasswordJsonAuthenticationListener implements ListenerInterface
  44. {
  45.     use LegacyListenerTrait;
  46.     private $tokenStorage;
  47.     private $authenticationManager;
  48.     private $httpUtils;
  49.     private $providerKey;
  50.     private $successHandler;
  51.     private $failureHandler;
  52.     private $options;
  53.     private $logger;
  54.     private $eventDispatcher;
  55.     private $propertyAccessor;
  56.     private $sessionStrategy;
  57.     public function __construct(TokenStorageInterface $tokenStorageAuthenticationManagerInterface $authenticationManagerHttpUtils $httpUtilsstring $providerKeyAuthenticationSuccessHandlerInterface $successHandler nullAuthenticationFailureHandlerInterface $failureHandler null, array $options = [], LoggerInterface $logger nullEventDispatcherInterface $eventDispatcher nullPropertyAccessorInterface $propertyAccessor null)
  58.     {
  59.         $this->tokenStorage $tokenStorage;
  60.         $this->authenticationManager $authenticationManager;
  61.         $this->httpUtils $httpUtils;
  62.         $this->providerKey $providerKey;
  63.         $this->successHandler $successHandler;
  64.         $this->failureHandler $failureHandler;
  65.         $this->logger $logger;
  66.         $this->eventDispatcher LegacyEventDispatcherProxy::decorate($eventDispatcher);
  67.         $this->options array_merge(['username_path' => 'username''password_path' => 'password'], $options);
  68.         $this->propertyAccessor $propertyAccessor ?: PropertyAccess::createPropertyAccessor();
  69.     }
  70.     /**
  71.      * {@inheritdoc}
  72.      */
  73.     public function __invoke(RequestEvent $event)
  74.     {
  75.         $request $event->getRequest();
  76.         if (false === strpos($request->getRequestFormat(), 'json')
  77.             && false === strpos($request->getContentType(), 'json')
  78.         ) {
  79.             return;
  80.         }
  81.         if (isset($this->options['check_path']) && !$this->httpUtils->checkRequestPath($request$this->options['check_path'])) {
  82.             return;
  83.         }
  84.         $data json_decode($request->getContent());
  85.         try {
  86.             if (!$data instanceof \stdClass) {
  87.                 throw new BadRequestHttpException('Invalid JSON.');
  88.             }
  89.             try {
  90.                 $username $this->propertyAccessor->getValue($data$this->options['username_path']);
  91.             } catch (AccessException $e) {
  92.                 throw new BadRequestHttpException(sprintf('The key "%s" must be provided.'$this->options['username_path']), $e);
  93.             }
  94.             try {
  95.                 $password $this->propertyAccessor->getValue($data$this->options['password_path']);
  96.             } catch (AccessException $e) {
  97.                 throw new BadRequestHttpException(sprintf('The key "%s" must be provided.'$this->options['password_path']), $e);
  98.             }
  99.             if (!\is_string($username)) {
  100.                 throw new BadRequestHttpException(sprintf('The key "%s" must be a string.'$this->options['username_path']));
  101.             }
  102.             if (\strlen($username) > Security::MAX_USERNAME_LENGTH) {
  103.                 throw new BadCredentialsException('Invalid username.');
  104.             }
  105.             if (!\is_string($password)) {
  106.                 throw new BadRequestHttpException(sprintf('The key "%s" must be a string.'$this->options['password_path']));
  107.             }
  108.             $token = new UsernamePasswordToken($username$password$this->providerKey);
  109.             $authenticatedToken $this->authenticationManager->authenticate($token);
  110.             $response $this->onSuccess($request$authenticatedToken);
  111.         } catch (AuthenticationException $e) {
  112.             $response $this->onFailure($request$e);
  113.         } catch (BadRequestHttpException $e) {
  114.             $request->setRequestFormat('json');
  115.             throw $e;
  116.         }
  117.         if (null === $response) {
  118.             return;
  119.         }
  120.         $event->setResponse($response);
  121.     }
  122.     private function onSuccess(Request $requestTokenInterface $token)
  123.     {
  124.         if (null !== $this->logger) {
  125.             $this->logger->info('User has been authenticated successfully.', ['username' => $token->getUsername()]);
  126.         }
  127.         $this->migrateSession($request$token);
  128.         $this->tokenStorage->setToken($token);
  129.         if (null !== $this->eventDispatcher) {
  130.             $loginEvent = new InteractiveLoginEvent($request$token);
  131.             $this->eventDispatcher->dispatch($loginEventSecurityEvents::INTERACTIVE_LOGIN);
  132.         }
  133.         if (!$this->successHandler) {
  134.             return; // let the original request succeeds
  135.         }
  136.         $response $this->successHandler->onAuthenticationSuccess($request$token);
  137.         if (!$response instanceof Response) {
  138.             throw new \RuntimeException('Authentication Success Handler did not return a Response.');
  139.         }
  140.         return $response;
  141.     }
  142.     private function onFailure(Request $requestAuthenticationException $failed)
  143.     {
  144.         if (null !== $this->logger) {
  145.             $this->logger->info('Authentication request failed.', ['exception' => $failed]);
  146.         }
  147.         $token $this->tokenStorage->getToken();
  148.         if ($token instanceof UsernamePasswordToken && $this->providerKey === $token->getProviderKey()) {
  149.             $this->tokenStorage->setToken(null);
  150.         }
  151.         if (!$this->failureHandler) {
  152.             return new JsonResponse(['error' => $failed->getMessageKey()], 401);
  153.         }
  154.         $response $this->failureHandler->onAuthenticationFailure($request$failed);
  155.         if (!$response instanceof Response) {
  156.             throw new \RuntimeException('Authentication Failure Handler did not return a Response.');
  157.         }
  158.         return $response;
  159.     }
  160.     /**
  161.      * Call this method if your authentication token is stored to a session.
  162.      *
  163.      * @final
  164.      */
  165.     public function setSessionAuthenticationStrategy(SessionAuthenticationStrategyInterface $sessionStrategy)
  166.     {
  167.         $this->sessionStrategy $sessionStrategy;
  168.     }
  169.     private function migrateSession(Request $requestTokenInterface $token)
  170.     {
  171.         if (!$this->sessionStrategy || !$request->hasSession() || !$request->hasPreviousSession()) {
  172.             return;
  173.         }
  174.         $this->sessionStrategy->onAuthentication($request$token);
  175.     }
  176. }