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

Open in your IDE?
  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 $tokenStorage;
  43.     private string $sessionKey;
  44.     private $logger;
  45.     private iterable $userProviders;
  46.     private $dispatcher;
  47.     private bool $registered false;
  48.     private $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 || $sessionTrackerEnabler instanceof \Closure $sessionTrackerEnabler \Closure::fromCallable($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.         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.             $originalToken $token;
  113.             $token $this->refreshUser($token);
  114.             if (!$token) {
  115.                 if ($this->logger) {
  116.                     $this->logger->debug('Token was deauthenticated after trying to refresh it.');
  117.                 }
  118.                 if ($this->dispatcher) {
  119.                     $this->dispatcher->dispatch(new TokenDeauthenticatedEvent($originalToken$request));
  120.                 }
  121.             }
  122.         } elseif (null !== $token) {
  123.             if (null !== $this->logger) {
  124.                 $this->logger->warning('Expected a security token from the session, got something else.', ['key' => $this->sessionKey'received' => $token]);
  125.             }
  126.             $token null;
  127.         }
  128.         if ($this->sessionTrackerEnabler) {
  129.             ($this->sessionTrackerEnabler)();
  130.         }
  131.         $this->tokenStorage->setToken($token);
  132.     }
  133.     /**
  134.      * Writes the security token into the session.
  135.      */
  136.     public function onKernelResponse(ResponseEvent $event)
  137.     {
  138.         if (!$event->isMainRequest()) {
  139.             return;
  140.         }
  141.         $request $event->getRequest();
  142.         if (!$request->hasSession() || $request->attributes->get('_security_firewall_run') !== $this->sessionKey) {
  143.             return;
  144.         }
  145.         if ($this->dispatcher) {
  146.             $this->dispatcher->removeListener(KernelEvents::RESPONSE, [$this'onKernelResponse']);
  147.         }
  148.         $this->registered false;
  149.         $session $request->getSession();
  150.         $sessionId $session->getId();
  151.         $usageIndexValue $session instanceof Session $usageIndexReference = &$session->getUsageIndex() : null;
  152.         $token $this->tokenStorage->getToken();
  153.         if (!$this->trustResolver->isAuthenticated($token)) {
  154.             if ($request->hasPreviousSession()) {
  155.                 $session->remove($this->sessionKey);
  156.             }
  157.         } else {
  158.             $session->set($this->sessionKeyserialize($token));
  159.             if (null !== $this->logger) {
  160.                 $this->logger->debug('Stored the security token in the session.', ['key' => $this->sessionKey]);
  161.             }
  162.         }
  163.         if ($this->sessionTrackerEnabler && $session->getId() === $sessionId) {
  164.             $usageIndexReference $usageIndexValue;
  165.         }
  166.     }
  167.     /**
  168.      * Refreshes the user by reloading it from the user provider.
  169.      *
  170.      * @throws \RuntimeException
  171.      */
  172.     protected function refreshUser(TokenInterface $token): ?TokenInterface
  173.     {
  174.         $user $token->getUser();
  175.         $userNotFoundByProvider false;
  176.         $userDeauthenticated false;
  177.         $userClass \get_class($user);
  178.         foreach ($this->userProviders as $provider) {
  179.             if (!$provider instanceof UserProviderInterface) {
  180.                 throw new \InvalidArgumentException(sprintf('User provider "%s" must implement "%s".'get_debug_type($provider), UserProviderInterface::class));
  181.             }
  182.             if (!$provider->supportsClass($userClass)) {
  183.                 continue;
  184.             }
  185.             try {
  186.                 $refreshedUser $provider->refreshUser($user);
  187.                 $newToken = clone $token;
  188.                 $newToken->setUser($refreshedUserfalse);
  189.                 // tokens can be deauthenticated if the user has been changed.
  190.                 if ($token instanceof AbstractToken && $this->hasUserChanged($user$newToken)) {
  191.                     $userDeauthenticated true;
  192.                     if (null !== $this->logger) {
  193.                         $this->logger->debug('Cannot refresh token because user has changed.', ['username' => $refreshedUser->getUserIdentifier(), 'provider' => \get_class($provider)]);
  194.                     }
  195.                     continue;
  196.                 }
  197.                 $token->setUser($refreshedUser);
  198.                 if (null !== $this->logger) {
  199.                     $context = ['provider' => \get_class($provider), 'username' => $refreshedUser->getUserIdentifier()];
  200.                     if ($token instanceof SwitchUserToken) {
  201.                         $originalToken $token->getOriginalToken();
  202.                         $context['impersonator_username'] = $originalToken->getUserIdentifier();
  203.                     }
  204.                     $this->logger->debug('User was reloaded from a user provider.'$context);
  205.                 }
  206.                 return $token;
  207.             } catch (UnsupportedUserException $e) {
  208.                 // let's try the next user provider
  209.             } catch (UserNotFoundException $e) {
  210.                 if (null !== $this->logger) {
  211.                     $this->logger->warning('Username could not be found in the selected user provider.', ['username' => $e->getUserIdentifier(), 'provider' => \get_class($provider)]);
  212.                 }
  213.                 $userNotFoundByProvider true;
  214.             }
  215.         }
  216.         if ($userDeauthenticated) {
  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.         $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 (\ErrorException $e) {
  237.             if (0x37313BC !== $e->getCode()) {
  238.                 throw $e;
  239.             }
  240.             if ($this->logger) {
  241.                 $this->logger->warning('Failed to unserialize the security token from the session.', ['key' => $this->sessionKey'received' => $serializedToken'exception' => $e]);
  242.             }
  243.         } finally {
  244.             restore_error_handler();
  245.             ini_set('unserialize_callback_func'$prevUnserializeHandler);
  246.         }
  247.         return $token;
  248.     }
  249.     private static function hasUserChanged(UserInterface $originalUserTokenInterface $refreshedToken): bool
  250.     {
  251.         $refreshedUser $refreshedToken->getUser();
  252.         if ($originalUser instanceof EquatableInterface) {
  253.             return !(bool) $originalUser->isEqualTo($refreshedUser);
  254.         }
  255.         if ($originalUser instanceof PasswordAuthenticatedUserInterface || $refreshedUser instanceof PasswordAuthenticatedUserInterface) {
  256.             if (!$originalUser instanceof PasswordAuthenticatedUserInterface || !$refreshedUser instanceof PasswordAuthenticatedUserInterface || $originalUser->getPassword() !== $refreshedUser->getPassword()) {
  257.                 return true;
  258.             }
  259.             if ($originalUser instanceof LegacyPasswordAuthenticatedUserInterface xor $refreshedUser instanceof LegacyPasswordAuthenticatedUserInterface) {
  260.                 return true;
  261.             }
  262.             if ($originalUser instanceof LegacyPasswordAuthenticatedUserInterface && $refreshedUser instanceof LegacyPasswordAuthenticatedUserInterface && $originalUser->getSalt() !== $refreshedUser->getSalt()) {
  263.                 return true;
  264.             }
  265.         }
  266.         $userRoles array_map('strval', (array) $refreshedUser->getRoles());
  267.         if ($refreshedToken instanceof SwitchUserToken) {
  268.             $userRoles[] = 'ROLE_PREVIOUS_ADMIN';
  269.         }
  270.         if (
  271.             \count($userRoles) !== \count($refreshedToken->getRoleNames()) ||
  272.             \count($userRoles) !== \count(array_intersect($userRoles$refreshedToken->getRoleNames()))
  273.         ) {
  274.             return true;
  275.         }
  276.         if ($originalUser->getUserIdentifier() !== $refreshedUser->getUserIdentifier()) {
  277.             return true;
  278.         }
  279.         return false;
  280.     }
  281.     /**
  282.      * @internal
  283.      */
  284.     public static function handleUnserializeCallback(string $class)
  285.     {
  286.         throw new \ErrorException('Class not found: '.$class0x37313BC);
  287.     }
  288. }