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

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