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

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