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

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