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

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.                         // @deprecated since Symfony 5.3, change to $token->getUserIdentifier() in 6.0
  210.                         $context['impersonator_username'] = method_exists($token'getUserIdentifier') ? $token->getUserIdentifier() : $token->getOriginalToken()->getUsername();
  211.                     }
  212.                     $this->logger->debug('User was reloaded from a user provider.'$context);
  213.                 }
  214.                 return $token;
  215.             } catch (UnsupportedUserException $e) {
  216.                 // let's try the next user provider
  217.             } catch (UserNotFoundException $e) {
  218.                 if (null !== $this->logger) {
  219.                     $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)]);
  220.                 }
  221.                 $userNotFoundByProvider true;
  222.             }
  223.         }
  224.         if ($userDeauthenticated) {
  225.             if (null !== $this->logger) {
  226.                 $this->logger->debug('Token was deauthenticated after trying to refresh it.');
  227.             }
  228.             if ($this->dispatcher) {
  229.                 $this->dispatcher->dispatch(new DeauthenticatedEvent($token$newToken), DeauthenticatedEvent::class);
  230.             }
  231.             return null;
  232.         }
  233.         if ($userNotFoundByProvider) {
  234.             return null;
  235.         }
  236.         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));
  237.     }
  238.     private function safelyUnserialize(string $serializedToken)
  239.     {
  240.         $e $token null;
  241.         $prevUnserializeHandler ini_set('unserialize_callback_func'__CLASS__.'::handleUnserializeCallback');
  242.         $prevErrorHandler set_error_handler(function ($type$msg$file$line$context = []) use (&$prevErrorHandler) {
  243.             if (__FILE__ === $file) {
  244.                 throw new \ErrorException($msg0x37313bc$type$file$line);
  245.             }
  246.             return $prevErrorHandler $prevErrorHandler($type$msg$file$line$context) : false;
  247.         });
  248.         try {
  249.             $token unserialize($serializedToken);
  250.         } catch (\Throwable $e) {
  251.         }
  252.         restore_error_handler();
  253.         ini_set('unserialize_callback_func'$prevUnserializeHandler);
  254.         if ($e) {
  255.             if (!$e instanceof \ErrorException || 0x37313bc !== $e->getCode()) {
  256.                 throw $e;
  257.             }
  258.             if ($this->logger) {
  259.                 $this->logger->warning('Failed to unserialize the security token from the session.', ['key' => $this->sessionKey'received' => $serializedToken'exception' => $e]);
  260.             }
  261.         }
  262.         return $token;
  263.     }
  264.     /**
  265.      * @internal
  266.      */
  267.     public static function handleUnserializeCallback(string $class)
  268.     {
  269.         throw new \ErrorException('Class not found: '.$class0x37313bc);
  270.     }
  271.     public function setRememberMeServices(RememberMeServicesInterface $rememberMeServices)
  272.     {
  273.         $this->rememberMeServices $rememberMeServices;
  274.     }
  275. }