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

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