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 extends AbstractListener 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.         if (null !== $eventDispatcher && class_exists(LegacyEventDispatcherProxy::class)) {
  67.             $this->eventDispatcher LegacyEventDispatcherProxy::decorate($eventDispatcher);
  68.         } else {
  69.             $this->eventDispatcher $eventDispatcher;
  70.         }
  71.         $this->options array_merge(['username_path' => 'username''password_path' => 'password'], $options);
  72.         $this->propertyAccessor $propertyAccessor ?: PropertyAccess::createPropertyAccessor();
  73.     }
  74.     public function supports(Request $request): ?bool
  75.     {
  76.         if (false === strpos($request->getRequestFormat(), 'json')
  77.             && false === strpos($request->getContentType(), 'json')
  78.         ) {
  79.             return false;
  80.         }
  81.         if (isset($this->options['check_path']) && !$this->httpUtils->checkRequestPath($request$this->options['check_path'])) {
  82.             return false;
  83.         }
  84.         return true;
  85.     }
  86.     /**
  87.      * {@inheritdoc}
  88.      */
  89.     public function authenticate(RequestEvent $event)
  90.     {
  91.         $request $event->getRequest();
  92.         $data json_decode($request->getContent());
  93.         try {
  94.             if (!$data instanceof \stdClass) {
  95.                 throw new BadRequestHttpException('Invalid JSON.');
  96.             }
  97.             try {
  98.                 $username $this->propertyAccessor->getValue($data$this->options['username_path']);
  99.             } catch (AccessException $e) {
  100.                 throw new BadRequestHttpException(sprintf('The key "%s" must be provided.'$this->options['username_path']), $e);
  101.             }
  102.             try {
  103.                 $password $this->propertyAccessor->getValue($data$this->options['password_path']);
  104.             } catch (AccessException $e) {
  105.                 throw new BadRequestHttpException(sprintf('The key "%s" must be provided.'$this->options['password_path']), $e);
  106.             }
  107.             if (!\is_string($username)) {
  108.                 throw new BadRequestHttpException(sprintf('The key "%s" must be a string.'$this->options['username_path']));
  109.             }
  110.             if (\strlen($username) > Security::MAX_USERNAME_LENGTH) {
  111.                 throw new BadCredentialsException('Invalid username.');
  112.             }
  113.             if (!\is_string($password)) {
  114.                 throw new BadRequestHttpException(sprintf('The key "%s" must be a string.'$this->options['password_path']));
  115.             }
  116.             $token = new UsernamePasswordToken($username$password$this->providerKey);
  117.             $authenticatedToken $this->authenticationManager->authenticate($token);
  118.             $response $this->onSuccess($request$authenticatedToken);
  119.         } catch (AuthenticationException $e) {
  120.             $response $this->onFailure($request$e);
  121.         } catch (BadRequestHttpException $e) {
  122.             $request->setRequestFormat('json');
  123.             throw $e;
  124.         }
  125.         if (null === $response) {
  126.             return;
  127.         }
  128.         $event->setResponse($response);
  129.     }
  130.     private function onSuccess(Request $requestTokenInterface $token): ?Response
  131.     {
  132.         if (null !== $this->logger) {
  133.             $this->logger->info('User has been authenticated successfully.', ['username' => $token->getUsername()]);
  134.         }
  135.         $this->migrateSession($request$token);
  136.         $this->tokenStorage->setToken($token);
  137.         if (null !== $this->eventDispatcher) {
  138.             $loginEvent = new InteractiveLoginEvent($request$token);
  139.             $this->eventDispatcher->dispatch($loginEventSecurityEvents::INTERACTIVE_LOGIN);
  140.         }
  141.         if (!$this->successHandler) {
  142.             return null// let the original request succeeds
  143.         }
  144.         $response $this->successHandler->onAuthenticationSuccess($request$token);
  145.         if (!$response instanceof Response) {
  146.             throw new \RuntimeException('Authentication Success Handler did not return a Response.');
  147.         }
  148.         return $response;
  149.     }
  150.     private function onFailure(Request $requestAuthenticationException $failed): Response
  151.     {
  152.         if (null !== $this->logger) {
  153.             $this->logger->info('Authentication request failed.', ['exception' => $failed]);
  154.         }
  155.         $token $this->tokenStorage->getToken();
  156.         if ($token instanceof UsernamePasswordToken && $this->providerKey === $token->getProviderKey()) {
  157.             $this->tokenStorage->setToken(null);
  158.         }
  159.         if (!$this->failureHandler) {
  160.             return new JsonResponse(['error' => $failed->getMessageKey()], 401);
  161.         }
  162.         $response $this->failureHandler->onAuthenticationFailure($request$failed);
  163.         if (!$response instanceof Response) {
  164.             throw new \RuntimeException('Authentication Failure Handler did not return a Response.');
  165.         }
  166.         return $response;
  167.     }
  168.     /**
  169.      * Call this method if your authentication token is stored to a session.
  170.      *
  171.      * @final
  172.      */
  173.     public function setSessionAuthenticationStrategy(SessionAuthenticationStrategyInterface $sessionStrategy)
  174.     {
  175.         $this->sessionStrategy $sessionStrategy;
  176.     }
  177.     private function migrateSession(Request $requestTokenInterface $token)
  178.     {
  179.         if (!$this->sessionStrategy || !$request->hasSession() || !$request->hasPreviousSession()) {
  180.             return;
  181.         }
  182.         $this->sessionStrategy->onAuthentication($request$token);
  183.     }
  184. }