vendor/symfony/security-http/Authenticator/JsonLoginAuthenticator.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\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\Authenticator\Passport\PassportInterface;
  32. use Symfony\Component\Security\Http\HttpUtils;
  33. use Symfony\Contracts\Translation\TranslatorInterface;
  34. /**
  35.  * Provides a stateless implementation of an authentication via
  36.  * a JSON document composed of a username and a password.
  37.  *
  38.  * @author Kévin Dunglas <dunglas@gmail.com>
  39.  * @author Wouter de Jong <wouter@wouterj.nl>
  40.  *
  41.  * @final
  42.  */
  43. class JsonLoginAuthenticator implements InteractiveAuthenticatorInterface
  44. {
  45.     private $options;
  46.     private $httpUtils;
  47.     private $userProvider;
  48.     private $propertyAccessor;
  49.     private $successHandler;
  50.     private $failureHandler;
  51.     /**
  52.      * @var TranslatorInterface|null
  53.      */
  54.     private $translator;
  55.     public function __construct(HttpUtils $httpUtilsUserProviderInterface $userProviderAuthenticationSuccessHandlerInterface $successHandler nullAuthenticationFailureHandlerInterface $failureHandler null, array $options = [], PropertyAccessorInterface $propertyAccessor null)
  56.     {
  57.         $this->options array_merge(['username_path' => 'username''password_path' => 'password'], $options);
  58.         $this->httpUtils $httpUtils;
  59.         $this->successHandler $successHandler;
  60.         $this->failureHandler $failureHandler;
  61.         $this->userProvider $userProvider;
  62.         $this->propertyAccessor $propertyAccessor ?: PropertyAccess::createPropertyAccessor();
  63.     }
  64.     public function supports(Request $request): ?bool
  65.     {
  66.         if (false === strpos($request->getRequestFormat() ?? '''json') && false === strpos($request->getContentType() ?? '''json')) {
  67.             return false;
  68.         }
  69.         if (isset($this->options['check_path']) && !$this->httpUtils->checkRequestPath($request$this->options['check_path'])) {
  70.             return false;
  71.         }
  72.         return true;
  73.     }
  74.     public function authenticate(Request $request): PassportInterface
  75.     {
  76.         try {
  77.             $credentials $this->getCredentials($request);
  78.         } catch (BadRequestHttpException $e) {
  79.             $request->setRequestFormat('json');
  80.             throw $e;
  81.         }
  82.         // @deprecated since Symfony 5.3, change to $this->userProvider->loadUserByIdentifier() in 6.0
  83.         $method 'loadUserByIdentifier';
  84.         if (!method_exists($this->userProvider'loadUserByIdentifier')) {
  85.             trigger_deprecation('symfony/security-core''5.3''Not implementing method "loadUserByIdentifier()" in user provider "%s" is deprecated. This method will replace "loadUserByUsername()" in Symfony 6.0.'get_debug_type($this->userProvider));
  86.             $method 'loadUserByUsername';
  87.         }
  88.         $passport = new Passport(
  89.             new UserBadge($credentials['username'], [$this->userProvider$method]),
  90.             new PasswordCredentials($credentials['password'])
  91.         );
  92.         if ($this->userProvider instanceof PasswordUpgraderInterface) {
  93.             $passport->addBadge(new PasswordUpgradeBadge($credentials['password'], $this->userProvider));
  94.         }
  95.         return $passport;
  96.     }
  97.     /**
  98.      * @deprecated since Symfony 5.4, use {@link createToken()} instead
  99.      */
  100.     public function createAuthenticatedToken(PassportInterface $passportstring $firewallName): TokenInterface
  101.     {
  102.         trigger_deprecation('symfony/security-http''5.4''Method "%s()" is deprecated, use "%s::createToken()" instead.'__METHOD____CLASS__);
  103.         return $this->createToken($passport$firewallName);
  104.     }
  105.     public function createToken(Passport $passportstring $firewallName): TokenInterface
  106.     {
  107.         return new UsernamePasswordToken($passport->getUser(), $firewallName$passport->getUser()->getRoles());
  108.     }
  109.     public function onAuthenticationSuccess(Request $requestTokenInterface $tokenstring $firewallName): ?Response
  110.     {
  111.         if (null === $this->successHandler) {
  112.             return null// let the original request continue
  113.         }
  114.         return $this->successHandler->onAuthenticationSuccess($request$token);
  115.     }
  116.     public function onAuthenticationFailure(Request $requestAuthenticationException $exception): ?Response
  117.     {
  118.         if (null === $this->failureHandler) {
  119.             if (null !== $this->translator) {
  120.                 $errorMessage $this->translator->trans($exception->getMessageKey(), $exception->getMessageData(), 'security');
  121.             } else {
  122.                 $errorMessage strtr($exception->getMessageKey(), $exception->getMessageData());
  123.             }
  124.             return new JsonResponse(['error' => $errorMessage], JsonResponse::HTTP_UNAUTHORIZED);
  125.         }
  126.         return $this->failureHandler->onAuthenticationFailure($request$exception);
  127.     }
  128.     public function isInteractive(): bool
  129.     {
  130.         return true;
  131.     }
  132.     public function setTranslator(TranslatorInterface $translator)
  133.     {
  134.         $this->translator $translator;
  135.     }
  136.     private function getCredentials(Request $request)
  137.     {
  138.         $data json_decode($request->getContent());
  139.         if (!$data instanceof \stdClass) {
  140.             throw new BadRequestHttpException('Invalid JSON.');
  141.         }
  142.         $credentials = [];
  143.         try {
  144.             $credentials['username'] = $this->propertyAccessor->getValue($data$this->options['username_path']);
  145.             if (!\is_string($credentials['username'])) {
  146.                 throw new BadRequestHttpException(sprintf('The key "%s" must be a string.'$this->options['username_path']));
  147.             }
  148.             if (\strlen($credentials['username']) > Security::MAX_USERNAME_LENGTH) {
  149.                 throw new BadCredentialsException('Invalid username.');
  150.             }
  151.         } catch (AccessException $e) {
  152.             throw new BadRequestHttpException(sprintf('The key "%s" must be provided.'$this->options['username_path']), $e);
  153.         }
  154.         try {
  155.             $credentials['password'] = $this->propertyAccessor->getValue($data$this->options['password_path']);
  156.             if (!\is_string($credentials['password'])) {
  157.                 throw new BadRequestHttpException(sprintf('The key "%s" must be a string.'$this->options['password_path']));
  158.             }
  159.         } catch (AccessException $e) {
  160.             throw new BadRequestHttpException(sprintf('The key "%s" must be provided.'$this->options['password_path']), $e);
  161.         }
  162.         return $credentials;
  163.     }
  164. }