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

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. trigger_deprecation('symfony/security-http''5.3''The "%s" class is deprecated, use the new authenticator system instead.'UsernamePasswordJsonAuthenticationListener::class);
  36. /**
  37.  * UsernamePasswordJsonAuthenticationListener is a stateless implementation of
  38.  * an authentication via a JSON document composed of a username and a password.
  39.  *
  40.  * @author Kévin Dunglas <dunglas@gmail.com>
  41.  *
  42.  * @deprecated since Symfony 5.3, use the new authenticator system instead
  43.  */
  44. class UsernamePasswordJsonAuthenticationListener extends AbstractListener
  45. {
  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.     /**
  58.      * @var TranslatorInterface|null
  59.      */
  60.     private $translator;
  61.     public function __construct(TokenStorageInterface $tokenStorageAuthenticationManagerInterface $authenticationManagerHttpUtils $httpUtilsstring $providerKeyAuthenticationSuccessHandlerInterface $successHandler nullAuthenticationFailureHandlerInterface $failureHandler null, array $options = [], LoggerInterface $logger nullEventDispatcherInterface $eventDispatcher nullPropertyAccessorInterface $propertyAccessor null)
  62.     {
  63.         $this->tokenStorage $tokenStorage;
  64.         $this->authenticationManager $authenticationManager;
  65.         $this->httpUtils $httpUtils;
  66.         $this->providerKey $providerKey;
  67.         $this->successHandler $successHandler;
  68.         $this->failureHandler $failureHandler;
  69.         $this->logger $logger;
  70.         $this->eventDispatcher $eventDispatcher;
  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 (!str_contains($request->getRequestFormat() ?? '''json')
  77.             && !str_contains($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.             // @deprecated since Symfony 5.3, change to $token->getUserIdentifier() in 6.0
  134.             $this->logger->info('User has been authenticated successfully.', ['username' => method_exists($token'getUserIdentifier') ? $token->getUserIdentifier() : $token->getUsername()]);
  135.         }
  136.         $this->migrateSession($request$token);
  137.         $this->tokenStorage->setToken($token);
  138.         if (null !== $this->eventDispatcher) {
  139.             $loginEvent = new InteractiveLoginEvent($request$token);
  140.             $this->eventDispatcher->dispatch($loginEventSecurityEvents::INTERACTIVE_LOGIN);
  141.         }
  142.         if (!$this->successHandler) {
  143.             return null// let the original request succeeds
  144.         }
  145.         $response $this->successHandler->onAuthenticationSuccess($request$token);
  146.         if (!$response instanceof Response) {
  147.             throw new \RuntimeException('Authentication Success Handler did not return a Response.');
  148.         }
  149.         return $response;
  150.     }
  151.     private function onFailure(Request $requestAuthenticationException $failed): Response
  152.     {
  153.         if (null !== $this->logger) {
  154.             $this->logger->info('Authentication request failed.', ['exception' => $failed]);
  155.         }
  156.         $token $this->tokenStorage->getToken();
  157.         if ($token instanceof UsernamePasswordToken && $this->providerKey === $token->getFirewallName()) {
  158.             $this->tokenStorage->setToken(null);
  159.         }
  160.         if (!$this->failureHandler) {
  161.             if (null !== $this->translator) {
  162.                 $errorMessage $this->translator->trans($failed->getMessageKey(), $failed->getMessageData(), 'security');
  163.             } else {
  164.                 $errorMessage strtr($failed->getMessageKey(), $failed->getMessageData());
  165.             }
  166.             return new JsonResponse(['error' => $errorMessage], 401);
  167.         }
  168.         $response $this->failureHandler->onAuthenticationFailure($request$failed);
  169.         if (!$response instanceof Response) {
  170.             throw new \RuntimeException('Authentication Failure Handler did not return a Response.');
  171.         }
  172.         return $response;
  173.     }
  174.     /**
  175.      * Call this method if your authentication token is stored to a session.
  176.      *
  177.      * @final
  178.      */
  179.     public function setSessionAuthenticationStrategy(SessionAuthenticationStrategyInterface $sessionStrategy)
  180.     {
  181.         $this->sessionStrategy $sessionStrategy;
  182.     }
  183.     public function setTranslator(TranslatorInterface $translator)
  184.     {
  185.         $this->translator $translator;
  186.     }
  187.     private function migrateSession(Request $requestTokenInterface $token)
  188.     {
  189.         if (!$this->sessionStrategy || !$request->hasSession() || !$request->hasPreviousSession()) {
  190.             return;
  191.         }
  192.         $this->sessionStrategy->onAuthentication($request$token);
  193.     }
  194. }