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

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