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

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