vendor/symfony/security-http/Firewall/ContextListener.php line 45

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\Event;
  13. use Symfony\Component\EventDispatcher\LegacyEventDispatcherProxy;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\HttpFoundation\Session\Session;
  16. use Symfony\Component\HttpKernel\Event\RequestEvent;
  17. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  18. use Symfony\Component\HttpKernel\KernelEvents;
  19. use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolver;
  20. use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface;
  21. use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
  22. use Symfony\Component\Security\Core\Authentication\Token\RememberMeToken;
  23. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  24. use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
  25. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  26. use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
  27. use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
  28. use Symfony\Component\Security\Core\User\UserInterface;
  29. use Symfony\Component\Security\Core\User\UserProviderInterface;
  30. use Symfony\Component\Security\Http\Event\DeauthenticatedEvent;
  31. use Symfony\Component\Security\Http\RememberMe\RememberMeServicesInterface;
  32. use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
  33. /**
  34.  * ContextListener manages the SecurityContext persistence through a session.
  35.  *
  36.  * @author Fabien Potencier <fabien@symfony.com>
  37.  * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  38.  *
  39.  * @final
  40.  */
  41. class ContextListener extends AbstractListener
  42. {
  43.     private $tokenStorage;
  44.     private $sessionKey;
  45.     private $logger;
  46.     private $userProviders;
  47.     private $dispatcher;
  48.     private $registered;
  49.     private $trustResolver;
  50.     private $rememberMeServices;
  51.     private $sessionTrackerEnabler;
  52.     /**
  53.      * @param iterable|UserProviderInterface[] $userProviders
  54.      */
  55.     public function __construct(TokenStorageInterface $tokenStorageiterable $userProvidersstring $contextKeyLoggerInterface $logger nullEventDispatcherInterface $dispatcher nullAuthenticationTrustResolverInterface $trustResolver null, callable $sessionTrackerEnabler null)
  56.     {
  57.         if (empty($contextKey)) {
  58.             throw new \InvalidArgumentException('$contextKey must not be empty.');
  59.         }
  60.         $this->tokenStorage $tokenStorage;
  61.         $this->userProviders $userProviders;
  62.         $this->sessionKey '_security_'.$contextKey;
  63.         $this->logger $logger;
  64.         $this->dispatcher class_exists(Event::class) ? LegacyEventDispatcherProxy::decorate($dispatcher) : $dispatcher;
  65.         $this->trustResolver $trustResolver ?? new AuthenticationTrustResolver(AnonymousToken::class, RememberMeToken::class);
  66.         $this->sessionTrackerEnabler $sessionTrackerEnabler;
  67.     }
  68.     /**
  69.      * {@inheritdoc}
  70.      */
  71.     public function supports(Request $request): ?bool
  72.     {
  73.         return null// always run authenticate() lazily with lazy firewalls
  74.     }
  75.     /**
  76.      * Reads the Security Token from the session.
  77.      */
  78.     public function authenticate(RequestEvent $event)
  79.     {
  80.         if (!$this->registered && null !== $this->dispatcher && $event->isMasterRequest()) {
  81.             $this->dispatcher->addListener(KernelEvents::RESPONSE, [$this'onKernelResponse']);
  82.             $this->registered true;
  83.         }
  84.         $request $event->getRequest();
  85.         $session $request->hasPreviousSession() && $request->hasSession() ? $request->getSession() : null;
  86.         if (null !== $session) {
  87.             $usageIndexValue $session instanceof Session $usageIndexReference = &$session->getUsageIndex() : 0;
  88.             $usageIndexReference = \PHP_INT_MIN;
  89.             $sessionId $request->cookies->all()[$session->getName()] ?? null;
  90.             $token $session->get($this->sessionKey);
  91.             // sessionId = true is used in the tests
  92.             if ($this->sessionTrackerEnabler && \in_array($sessionId, [true$session->getId()], true)) {
  93.                 $usageIndexReference $usageIndexValue;
  94.             } else {
  95.                 $usageIndexReference $usageIndexReference - \PHP_INT_MIN $usageIndexValue;
  96.             }
  97.         }
  98.         if (null === $session || null === $token) {
  99.             if ($this->sessionTrackerEnabler) {
  100.                 ($this->sessionTrackerEnabler)();
  101.             }
  102.             $this->tokenStorage->setToken(null);
  103.             return;
  104.         }
  105.         $token $this->safelyUnserialize($token);
  106.         if (null !== $this->logger) {
  107.             $this->logger->debug('Read existing security token from the session.', [
  108.                 'key' => $this->sessionKey,
  109.                 'token_class' => \is_object($token) ? \get_class($token) : null,
  110.             ]);
  111.         }
  112.         if ($token instanceof TokenInterface) {
  113.             $token $this->refreshUser($token);
  114.             if (!$token && $this->rememberMeServices) {
  115.                 $this->rememberMeServices->loginFail($request);
  116.             }
  117.         } elseif (null !== $token) {
  118.             if (null !== $this->logger) {
  119.                 $this->logger->warning('Expected a security token from the session, got something else.', ['key' => $this->sessionKey'received' => $token]);
  120.             }
  121.             $token null;
  122.         }
  123.         if ($this->sessionTrackerEnabler) {
  124.             ($this->sessionTrackerEnabler)();
  125.         }
  126.         $this->tokenStorage->setToken($token);
  127.     }
  128.     /**
  129.      * Writes the security token into the session.
  130.      */
  131.     public function onKernelResponse(ResponseEvent $event)
  132.     {
  133.         if (!$event->isMasterRequest()) {
  134.             return;
  135.         }
  136.         $request $event->getRequest();
  137.         if (!$request->hasSession()) {
  138.             return;
  139.         }
  140.         $this->dispatcher->removeListener(KernelEvents::RESPONSE, [$this'onKernelResponse']);
  141.         $this->registered false;
  142.         $session $request->getSession();
  143.         $sessionId $session->getId();
  144.         $usageIndexValue $session instanceof Session $usageIndexReference = &$session->getUsageIndex() : null;
  145.         $token $this->tokenStorage->getToken();
  146.         if (null === $token || $this->trustResolver->isAnonymous($token)) {
  147.             if ($request->hasPreviousSession()) {
  148.                 $session->remove($this->sessionKey);
  149.             }
  150.         } else {
  151.             $session->set($this->sessionKeyserialize($token));
  152.             if (null !== $this->logger) {
  153.                 $this->logger->debug('Stored the security token in the session.', ['key' => $this->sessionKey]);
  154.             }
  155.         }
  156.         if ($this->sessionTrackerEnabler && $session->getId() === $sessionId) {
  157.             $usageIndexReference $usageIndexValue;
  158.         }
  159.     }
  160.     /**
  161.      * Refreshes the user by reloading it from the user provider.
  162.      *
  163.      * @throws \RuntimeException
  164.      */
  165.     protected function refreshUser(TokenInterface $token): ?TokenInterface
  166.     {
  167.         $user $token->getUser();
  168.         if (!$user instanceof UserInterface) {
  169.             return $token;
  170.         }
  171.         $userNotFoundByProvider false;
  172.         $userDeauthenticated false;
  173.         $userClass = \get_class($user);
  174.         foreach ($this->userProviders as $provider) {
  175.             if (!$provider instanceof UserProviderInterface) {
  176.                 throw new \InvalidArgumentException(sprintf('User provider "%s" must implement "%s".'get_debug_type($provider), UserProviderInterface::class));
  177.             }
  178.             if (!$provider->supportsClass($userClass)) {
  179.                 continue;
  180.             }
  181.             try {
  182.                 $refreshedUser $provider->refreshUser($user);
  183.                 $newToken = clone $token;
  184.                 $newToken->setUser($refreshedUser);
  185.                 // tokens can be deauthenticated if the user has been changed.
  186.                 if (!$newToken->isAuthenticated()) {
  187.                     $userDeauthenticated true;
  188.                     if (null !== $this->logger) {
  189.                         $this->logger->debug('Cannot refresh token because user has changed.', ['username' => $refreshedUser->getUsername(), 'provider' => \get_class($provider)]);
  190.                     }
  191.                     continue;
  192.                 }
  193.                 $token->setUser($refreshedUser);
  194.                 if (null !== $this->logger) {
  195.                     $context = ['provider' => \get_class($provider), 'username' => $refreshedUser->getUsername()];
  196.                     if ($token instanceof SwitchUserToken) {
  197.                         $context['impersonator_username'] = $token->getOriginalToken()->getUsername();
  198.                     }
  199.                     $this->logger->debug('User was reloaded from a user provider.'$context);
  200.                 }
  201.                 return $token;
  202.             } catch (UnsupportedUserException $e) {
  203.                 // let's try the next user provider
  204.             } catch (UsernameNotFoundException $e) {
  205.                 if (null !== $this->logger) {
  206.                     $this->logger->warning('Username could not be found in the selected user provider.', ['username' => $e->getUsername(), 'provider' => \get_class($provider)]);
  207.                 }
  208.                 $userNotFoundByProvider true;
  209.             }
  210.         }
  211.         if ($userDeauthenticated) {
  212.             if (null !== $this->logger) {
  213.                 $this->logger->debug('Token was deauthenticated after trying to refresh it.');
  214.             }
  215.             if (null !== $this->dispatcher) {
  216.                 $this->dispatcher->dispatch(new DeauthenticatedEvent($token$newToken), DeauthenticatedEvent::class);
  217.             }
  218.             return null;
  219.         }
  220.         if ($userNotFoundByProvider) {
  221.             return null;
  222.         }
  223.         throw new \RuntimeException(sprintf('There is no user provider for user "%s". Shouldn\'t the "supportsClass()" method of your user provider return true for this classname?'$userClass));
  224.     }
  225.     private function safelyUnserialize(string $serializedToken)
  226.     {
  227.         $e $token null;
  228.         $prevUnserializeHandler ini_set('unserialize_callback_func'__CLASS__.'::handleUnserializeCallback');
  229.         $prevErrorHandler set_error_handler(function ($type$msg$file$line$context = []) use (&$prevErrorHandler) {
  230.             if (__FILE__ === $file) {
  231.                 throw new \ErrorException($msg0x37313bc$type$file$line);
  232.             }
  233.             return $prevErrorHandler $prevErrorHandler($type$msg$file$line$context) : false;
  234.         });
  235.         try {
  236.             $token unserialize($serializedToken);
  237.         } catch (\Throwable $e) {
  238.         }
  239.         restore_error_handler();
  240.         ini_set('unserialize_callback_func'$prevUnserializeHandler);
  241.         if ($e) {
  242.             if (!$e instanceof \ErrorException || 0x37313bc !== $e->getCode()) {
  243.                 throw $e;
  244.             }
  245.             if ($this->logger) {
  246.                 $this->logger->warning('Failed to unserialize the security token from the session.', ['key' => $this->sessionKey'received' => $serializedToken'exception' => $e]);
  247.             }
  248.         }
  249.         return $token;
  250.     }
  251.     /**
  252.      * @internal
  253.      */
  254.     public static function handleUnserializeCallback($class)
  255.     {
  256.         throw new \ErrorException('Class not found: '.$class0x37313bc);
  257.     }
  258.     public function setRememberMeServices(RememberMeServicesInterface $rememberMeServices)
  259.     {
  260.         $this->rememberMeServices $rememberMeServices;
  261.     }
  262. }