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

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\EventDispatcher\EventDispatcherInterface;
  13. use Symfony\Component\HttpFoundation\JsonResponse;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\HttpFoundation\Response;
  16. use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  17. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  18. use Symfony\Component\PropertyAccess\Exception\AccessException;
  19. use Symfony\Component\PropertyAccess\PropertyAccess;
  20. use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
  21. use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
  22. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  23. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  24. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  25. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  26. use Symfony\Component\Security\Core\Exception\BadCredentialsException;
  27. use Symfony\Component\Security\Core\Security;
  28. use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
  29. use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
  30. use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
  31. use Symfony\Component\Security\Http\HttpUtils;
  32. use Symfony\Component\Security\Http\SecurityEvents;
  33. use Symfony\Component\Security\Http\Session\SessionAuthenticationStrategyInterface;
  34. /**
  35.  * UsernamePasswordJsonAuthenticationListener is a stateless implementation of
  36.  * an authentication via a JSON document composed of a username and a password.
  37.  *
  38.  * @author Kévin Dunglas <dunglas@gmail.com>
  39.  */
  40. class UsernamePasswordJsonAuthenticationListener implements ListenerInterface
  41. {
  42.     private $tokenStorage;
  43.     private $authenticationManager;
  44.     private $httpUtils;
  45.     private $providerKey;
  46.     private $successHandler;
  47.     private $failureHandler;
  48.     private $options;
  49.     private $logger;
  50.     private $eventDispatcher;
  51.     private $propertyAccessor;
  52.     private $sessionStrategy;
  53.     public function __construct(TokenStorageInterface $tokenStorageAuthenticationManagerInterface $authenticationManagerHttpUtils $httpUtilsstring $providerKeyAuthenticationSuccessHandlerInterface $successHandler nullAuthenticationFailureHandlerInterface $failureHandler null, array $options = [], LoggerInterface $logger nullEventDispatcherInterface $eventDispatcher nullPropertyAccessorInterface $propertyAccessor null)
  54.     {
  55.         $this->tokenStorage $tokenStorage;
  56.         $this->authenticationManager $authenticationManager;
  57.         $this->httpUtils $httpUtils;
  58.         $this->providerKey $providerKey;
  59.         $this->successHandler $successHandler;
  60.         $this->failureHandler $failureHandler;
  61.         $this->logger $logger;
  62.         $this->eventDispatcher $eventDispatcher;
  63.         $this->options array_merge(['username_path' => 'username''password_path' => 'password'], $options);
  64.         $this->propertyAccessor $propertyAccessor ?: PropertyAccess::createPropertyAccessor();
  65.     }
  66.     /**
  67.      * {@inheritdoc}
  68.      */
  69.     public function handle(GetResponseEvent $event)
  70.     {
  71.         $request $event->getRequest();
  72.         if (false === strpos($request->getRequestFormat(), 'json')
  73.             && false === strpos($request->getContentType(), 'json')
  74.         ) {
  75.             return;
  76.         }
  77.         if (isset($this->options['check_path']) && !$this->httpUtils->checkRequestPath($request$this->options['check_path'])) {
  78.             return;
  79.         }
  80.         $data json_decode($request->getContent());
  81.         try {
  82.             if (!$data instanceof \stdClass) {
  83.                 throw new BadRequestHttpException('Invalid JSON.');
  84.             }
  85.             try {
  86.                 $username $this->propertyAccessor->getValue($data$this->options['username_path']);
  87.             } catch (AccessException $e) {
  88.                 throw new BadRequestHttpException(sprintf('The key "%s" must be provided.'$this->options['username_path']), $e);
  89.             }
  90.             try {
  91.                 $password $this->propertyAccessor->getValue($data$this->options['password_path']);
  92.             } catch (AccessException $e) {
  93.                 throw new BadRequestHttpException(sprintf('The key "%s" must be provided.'$this->options['password_path']), $e);
  94.             }
  95.             if (!\is_string($username)) {
  96.                 throw new BadRequestHttpException(sprintf('The key "%s" must be a string.'$this->options['username_path']));
  97.             }
  98.             if (\strlen($username) > Security::MAX_USERNAME_LENGTH) {
  99.                 throw new BadCredentialsException('Invalid username.');
  100.             }
  101.             if (!\is_string($password)) {
  102.                 throw new BadRequestHttpException(sprintf('The key "%s" must be a string.'$this->options['password_path']));
  103.             }
  104.             $token = new UsernamePasswordToken($username$password$this->providerKey);
  105.             $authenticatedToken $this->authenticationManager->authenticate($token);
  106.             $response $this->onSuccess($request$authenticatedToken);
  107.         } catch (AuthenticationException $e) {
  108.             $response $this->onFailure($request$e);
  109.         } catch (BadRequestHttpException $e) {
  110.             $request->setRequestFormat('json');
  111.             throw $e;
  112.         }
  113.         if (null === $response) {
  114.             return;
  115.         }
  116.         $event->setResponse($response);
  117.     }
  118.     private function onSuccess(Request $requestTokenInterface $token)
  119.     {
  120.         if (null !== $this->logger) {
  121.             $this->logger->info('User has been authenticated successfully.', ['username' => $token->getUsername()]);
  122.         }
  123.         $this->migrateSession($request$token);
  124.         $this->tokenStorage->setToken($token);
  125.         if (null !== $this->eventDispatcher) {
  126.             $loginEvent = new InteractiveLoginEvent($request$token);
  127.             $this->eventDispatcher->dispatch(SecurityEvents::INTERACTIVE_LOGIN$loginEvent);
  128.         }
  129.         if (!$this->successHandler) {
  130.             return; // let the original request succeeds
  131.         }
  132.         $response $this->successHandler->onAuthenticationSuccess($request$token);
  133.         if (!$response instanceof Response) {
  134.             throw new \RuntimeException('Authentication Success Handler did not return a Response.');
  135.         }
  136.         return $response;
  137.     }
  138.     private function onFailure(Request $requestAuthenticationException $failed)
  139.     {
  140.         if (null !== $this->logger) {
  141.             $this->logger->info('Authentication request failed.', ['exception' => $failed]);
  142.         }
  143.         $token $this->tokenStorage->getToken();
  144.         if ($token instanceof UsernamePasswordToken && $this->providerKey === $token->getProviderKey()) {
  145.             $this->tokenStorage->setToken(null);
  146.         }
  147.         if (!$this->failureHandler) {
  148.             return new JsonResponse(['error' => $failed->getMessageKey()], 401);
  149.         }
  150.         $response $this->failureHandler->onAuthenticationFailure($request$failed);
  151.         if (!$response instanceof Response) {
  152.             throw new \RuntimeException('Authentication Failure Handler did not return a Response.');
  153.         }
  154.         return $response;
  155.     }
  156.     /**
  157.      * Call this method if your authentication token is stored to a session.
  158.      *
  159.      * @final
  160.      */
  161.     public function setSessionAuthenticationStrategy(SessionAuthenticationStrategyInterface $sessionStrategy)
  162.     {
  163.         $this->sessionStrategy $sessionStrategy;
  164.     }
  165.     private function migrateSession(Request $requestTokenInterface $token)
  166.     {
  167.         if (!$this->sessionStrategy || !$request->hasSession() || !$request->hasPreviousSession()) {
  168.             return;
  169.         }
  170.         $this->sessionStrategy->onAuthentication($request$token);
  171.     }
  172. }