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

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 $providerKey, ?AuthenticationSuccessHandlerInterface $successHandler null, ?AuthenticationFailureHandlerInterface $failureHandler null, array $options = [], ?LoggerInterface $logger null, ?EventDispatcherInterface $eventDispatcher null, ?PropertyAccessorInterface $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.         $previousToken $this->tokenStorage->getToken();
  94.         try {
  95.             if (!$data instanceof \stdClass) {
  96.                 throw new BadRequestHttpException('Invalid JSON.');
  97.             }
  98.             try {
  99.                 $username $this->propertyAccessor->getValue($data$this->options['username_path']);
  100.             } catch (AccessException $e) {
  101.                 throw new BadRequestHttpException(sprintf('The key "%s" must be provided.'$this->options['username_path']), $e);
  102.             }
  103.             try {
  104.                 $password $this->propertyAccessor->getValue($data$this->options['password_path']);
  105.             } catch (AccessException $e) {
  106.                 throw new BadRequestHttpException(sprintf('The key "%s" must be provided.'$this->options['password_path']), $e);
  107.             }
  108.             if (!\is_string($username)) {
  109.                 throw new BadRequestHttpException(sprintf('The key "%s" must be a string.'$this->options['username_path']));
  110.             }
  111.             if (\strlen($username) > Security::MAX_USERNAME_LENGTH) {
  112.                 throw new BadCredentialsException('Invalid username.');
  113.             }
  114.             if (!\is_string($password)) {
  115.                 throw new BadRequestHttpException(sprintf('The key "%s" must be a string.'$this->options['password_path']));
  116.             }
  117.             $token = new UsernamePasswordToken($username$password$this->providerKey);
  118.             $authenticatedToken $this->authenticationManager->authenticate($token);
  119.             $response $this->onSuccess($request$authenticatedToken$previousToken);
  120.         } catch (AuthenticationException $e) {
  121.             $response $this->onFailure($request$e);
  122.         } catch (BadRequestHttpException $e) {
  123.             $request->setRequestFormat('json');
  124.             throw $e;
  125.         }
  126.         if (null === $response) {
  127.             return;
  128.         }
  129.         $event->setResponse($response);
  130.     }
  131.     private function onSuccess(Request $requestTokenInterface $token, ?TokenInterface $previousToken): ?Response
  132.     {
  133.         if (null !== $this->logger) {
  134.             // @deprecated since Symfony 5.3, change to $token->getUserIdentifier() in 6.0
  135.             $this->logger->info('User has been authenticated successfully.', ['username' => method_exists($token'getUserIdentifier') ? $token->getUserIdentifier() : $token->getUsername()]);
  136.         }
  137.         $this->migrateSession($request$token$previousToken);
  138.         $this->tokenStorage->setToken($token);
  139.         if (null !== $this->eventDispatcher) {
  140.             $loginEvent = new InteractiveLoginEvent($request$token);
  141.             $this->eventDispatcher->dispatch($loginEventSecurityEvents::INTERACTIVE_LOGIN);
  142.         }
  143.         if (!$this->successHandler) {
  144.             return null// let the original request succeeds
  145.         }
  146.         $response $this->successHandler->onAuthenticationSuccess($request$token);
  147.         if (!$response instanceof Response) {
  148.             throw new \RuntimeException('Authentication Success Handler did not return a Response.');
  149.         }
  150.         return $response;
  151.     }
  152.     private function onFailure(Request $requestAuthenticationException $failed): Response
  153.     {
  154.         if (null !== $this->logger) {
  155.             $this->logger->info('Authentication request failed.', ['exception' => $failed]);
  156.         }
  157.         $token $this->tokenStorage->getToken();
  158.         if ($token instanceof UsernamePasswordToken && $this->providerKey === $token->getFirewallName()) {
  159.             $this->tokenStorage->setToken(null);
  160.         }
  161.         if (!$this->failureHandler) {
  162.             if (null !== $this->translator) {
  163.                 $errorMessage $this->translator->trans($failed->getMessageKey(), $failed->getMessageData(), 'security');
  164.             } else {
  165.                 $errorMessage strtr($failed->getMessageKey(), $failed->getMessageData());
  166.             }
  167.             return new JsonResponse(['error' => $errorMessage], 401);
  168.         }
  169.         $response $this->failureHandler->onAuthenticationFailure($request$failed);
  170.         if (!$response instanceof Response) {
  171.             throw new \RuntimeException('Authentication Failure Handler did not return a Response.');
  172.         }
  173.         return $response;
  174.     }
  175.     /**
  176.      * Call this method if your authentication token is stored to a session.
  177.      *
  178.      * @final
  179.      */
  180.     public function setSessionAuthenticationStrategy(SessionAuthenticationStrategyInterface $sessionStrategy)
  181.     {
  182.         $this->sessionStrategy $sessionStrategy;
  183.     }
  184.     public function setTranslator(TranslatorInterface $translator)
  185.     {
  186.         $this->translator $translator;
  187.     }
  188.     private function migrateSession(Request $requestTokenInterface $token, ?TokenInterface $previousToken)
  189.     {
  190.         if (!$this->sessionStrategy || !$request->hasSession() || !$request->hasPreviousSession()) {
  191.             return;
  192.         }
  193.         if ($previousToken) {
  194.             $user method_exists($token'getUserIdentifier') ? $token->getUserIdentifier() : $token->getUsername();
  195.             $previousUser method_exists($previousToken'getUserIdentifier') ? $previousToken->getUserIdentifier() : $previousToken->getUsername();
  196.             if ('' !== ($user ?? '') && $user === $previousUser) {
  197.                 return;
  198.             }
  199.         }
  200.         $this->sessionStrategy->onAuthentication($request$token);
  201.     }
  202. }