vendor/symfony/security-http/Authenticator/JsonLoginAuthenticator.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\Authenticator;
  11. use Symfony\Component\HttpFoundation\JsonResponse;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\HttpFoundation\Response;
  14. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  15. use Symfony\Component\PropertyAccess\Exception\AccessException;
  16. use Symfony\Component\PropertyAccess\PropertyAccess;
  17. use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
  18. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  19. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  20. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  21. use Symfony\Component\Security\Core\Exception\BadCredentialsException;
  22. use Symfony\Component\Security\Core\Security;
  23. use Symfony\Component\Security\Core\User\PasswordUpgraderInterface;
  24. use Symfony\Component\Security\Core\User\UserProviderInterface;
  25. use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
  26. use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
  27. use Symfony\Component\Security\Http\Authenticator\Passport\Badge\PasswordUpgradeBadge;
  28. use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
  29. use Symfony\Component\Security\Http\Authenticator\Passport\Credentials\PasswordCredentials;
  30. use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
  31. use Symfony\Component\Security\Http\HttpUtils;
  32. use Symfony\Contracts\Translation\TranslatorInterface;
  33. /**
  34.  * Provides a stateless implementation of an authentication via
  35.  * a JSON document composed of a username and a password.
  36.  *
  37.  * @author Kévin Dunglas <dunglas@gmail.com>
  38.  * @author Wouter de Jong <wouter@wouterj.nl>
  39.  *
  40.  * @final
  41.  */
  42. class JsonLoginAuthenticator implements InteractiveAuthenticatorInterface
  43. {
  44.     private array $options;
  45.     private HttpUtils $httpUtils;
  46.     private UserProviderInterface $userProvider;
  47.     private PropertyAccessorInterface $propertyAccessor;
  48.     private ?AuthenticationSuccessHandlerInterface $successHandler;
  49.     private ?AuthenticationFailureHandlerInterface $failureHandler;
  50.     private ?TranslatorInterface $translator null;
  51.     public function __construct(HttpUtils $httpUtilsUserProviderInterface $userProviderAuthenticationSuccessHandlerInterface $successHandler nullAuthenticationFailureHandlerInterface $failureHandler null, array $options = [], PropertyAccessorInterface $propertyAccessor null)
  52.     {
  53.         $this->options array_merge(['username_path' => 'username''password_path' => 'password'], $options);
  54.         $this->httpUtils $httpUtils;
  55.         $this->successHandler $successHandler;
  56.         $this->failureHandler $failureHandler;
  57.         $this->userProvider $userProvider;
  58.         $this->propertyAccessor $propertyAccessor ?: PropertyAccess::createPropertyAccessor();
  59.     }
  60.     public function supports(Request $request): ?bool
  61.     {
  62.         if (!str_contains($request->getRequestFormat() ?? '''json') && !str_contains($request->getContentType() ?? '''json')) {
  63.             return false;
  64.         }
  65.         if (isset($this->options['check_path']) && !$this->httpUtils->checkRequestPath($request$this->options['check_path'])) {
  66.             return false;
  67.         }
  68.         return true;
  69.     }
  70.     public function authenticate(Request $request): Passport
  71.     {
  72.         try {
  73.             $credentials $this->getCredentials($request);
  74.         } catch (BadRequestHttpException $e) {
  75.             $request->setRequestFormat('json');
  76.             throw $e;
  77.         }
  78.         $passport = new Passport(
  79.             new UserBadge($credentials['username'], $this->userProvider->loadUserByIdentifier(...)),
  80.             new PasswordCredentials($credentials['password'])
  81.         );
  82.         if ($this->userProvider instanceof PasswordUpgraderInterface) {
  83.             $passport->addBadge(new PasswordUpgradeBadge($credentials['password'], $this->userProvider));
  84.         }
  85.         return $passport;
  86.     }
  87.     public function createToken(Passport $passportstring $firewallName): TokenInterface
  88.     {
  89.         return new UsernamePasswordToken($passport->getUser(), $firewallName$passport->getUser()->getRoles());
  90.     }
  91.     public function onAuthenticationSuccess(Request $requestTokenInterface $tokenstring $firewallName): ?Response
  92.     {
  93.         if (null === $this->successHandler) {
  94.             return null// let the original request continue
  95.         }
  96.         return $this->successHandler->onAuthenticationSuccess($request$token);
  97.     }
  98.     public function onAuthenticationFailure(Request $requestAuthenticationException $exception): ?Response
  99.     {
  100.         if (null === $this->failureHandler) {
  101.             if (null !== $this->translator) {
  102.                 $errorMessage $this->translator->trans($exception->getMessageKey(), $exception->getMessageData(), 'security');
  103.             } else {
  104.                 $errorMessage strtr($exception->getMessageKey(), $exception->getMessageData());
  105.             }
  106.             return new JsonResponse(['error' => $errorMessage], JsonResponse::HTTP_UNAUTHORIZED);
  107.         }
  108.         return $this->failureHandler->onAuthenticationFailure($request$exception);
  109.     }
  110.     public function isInteractive(): bool
  111.     {
  112.         return true;
  113.     }
  114.     public function setTranslator(TranslatorInterface $translator)
  115.     {
  116.         $this->translator $translator;
  117.     }
  118.     private function getCredentials(Request $request)
  119.     {
  120.         $data json_decode($request->getContent());
  121.         if (!$data instanceof \stdClass) {
  122.             throw new BadRequestHttpException('Invalid JSON.');
  123.         }
  124.         $credentials = [];
  125.         try {
  126.             $credentials['username'] = $this->propertyAccessor->getValue($data$this->options['username_path']);
  127.             if (!\is_string($credentials['username'])) {
  128.                 throw new BadRequestHttpException(sprintf('The key "%s" must be a string.'$this->options['username_path']));
  129.             }
  130.             if (\strlen($credentials['username']) > Security::MAX_USERNAME_LENGTH) {
  131.                 throw new BadCredentialsException('Invalid username.');
  132.             }
  133.         } catch (AccessException $e) {
  134.             throw new BadRequestHttpException(sprintf('The key "%s" must be provided.'$this->options['username_path']), $e);
  135.         }
  136.         try {
  137.             $credentials['password'] = $this->propertyAccessor->getValue($data$this->options['password_path']);
  138.             if (!\is_string($credentials['password'])) {
  139.                 throw new BadRequestHttpException(sprintf('The key "%s" must be a string.'$this->options['password_path']));
  140.             }
  141.         } catch (AccessException $e) {
  142.             throw new BadRequestHttpException(sprintf('The key "%s" must be provided.'$this->options['password_path']), $e);
  143.         }
  144.         return $credentials;
  145.     }
  146. }