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