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

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.         $this->dispatcher LegacyEventDispatcherProxy::decorate($dispatcher);
  64.         $this->trustResolver $trustResolver ?: new AuthenticationTrustResolver(AnonymousToken::class, RememberMeToken::class);
  65.         $this->sessionTrackerEnabler $sessionTrackerEnabler;
  66.     }
  67.     /**
  68.      * {@inheritdoc}
  69.      */
  70.     public function supports(Request $request): ?bool
  71.     {
  72.         return null// always run authenticate() lazily with lazy firewalls
  73.     }
  74.     /**
  75.      * Reads the Security Token from the session.
  76.      */
  77.     public function authenticate(RequestEvent $event)
  78.     {
  79.         if (!$this->registered && null !== $this->dispatcher && $event->isMasterRequest()) {
  80.             $this->dispatcher->addListener(KernelEvents::RESPONSE, [$this'onKernelResponse']);
  81.             $this->registered true;
  82.         }
  83.         $request $event->getRequest();
  84.         $session $request->hasPreviousSession() && $request->hasSession() ? $request->getSession() : null;
  85.         if (null !== $session) {
  86.             $usageIndexValue $session instanceof Session $usageIndexReference = &$session->getUsageIndex() : 0;
  87.             $sessionId $session->getId();
  88.             $token $session->get($this->sessionKey);
  89.             if ($this->sessionTrackerEnabler && $session->getId() === $sessionId) {
  90.                 $usageIndexReference $usageIndexValue;
  91.             }
  92.         }
  93.         if (null === $session || null === $token) {
  94.             if ($this->sessionTrackerEnabler) {
  95.                 ($this->sessionTrackerEnabler)();
  96.             }
  97.             $this->tokenStorage->setToken(null);
  98.             return;
  99.         }
  100.         $token $this->safelyUnserialize($token);
  101.         if (null !== $this->logger) {
  102.             $this->logger->debug('Read existing security token from the session.', [
  103.                 'key' => $this->sessionKey,
  104.                 'token_class' => \is_object($token) ? \get_class($token) : null,
  105.             ]);
  106.         }
  107.         if ($token instanceof TokenInterface) {
  108.             $token $this->refreshUser($token);
  109.             if (!$token && $this->rememberMeServices) {
  110.                 $this->rememberMeServices->loginFail($request);
  111.             }
  112.         } elseif (null !== $token) {
  113.             if (null !== $this->logger) {
  114.                 $this->logger->warning('Expected a security token from the session, got something else.', ['key' => $this->sessionKey'received' => $token]);
  115.             }
  116.             $token null;
  117.         }
  118.         if ($this->sessionTrackerEnabler) {
  119.             ($this->sessionTrackerEnabler)();
  120.         }
  121.         $this->tokenStorage->setToken($token);
  122.     }
  123.     /**
  124.      * Writes the security token into the session.
  125.      */
  126.     public function onKernelResponse(ResponseEvent $event)
  127.     {
  128.         if (!$event->isMasterRequest()) {
  129.             return;
  130.         }
  131.         $request $event->getRequest();
  132.         if (!$request->hasSession()) {
  133.             return;
  134.         }
  135.         $this->dispatcher->removeListener(KernelEvents::RESPONSE, [$this'onKernelResponse']);
  136.         $this->registered false;
  137.         $session $request->getSession();
  138.         $sessionId $session->getId();
  139.         $usageIndexValue $session instanceof Session $usageIndexReference = &$session->getUsageIndex() : null;
  140.         $token $this->tokenStorage->getToken();
  141.         if (null === $token || $this->trustResolver->isAnonymous($token)) {
  142.             if ($request->hasPreviousSession()) {
  143.                 $session->remove($this->sessionKey);
  144.             }
  145.         } else {
  146.             $session->set($this->sessionKeyserialize($token));
  147.             if (null !== $this->logger) {
  148.                 $this->logger->debug('Stored the security token in the session.', ['key' => $this->sessionKey]);
  149.             }
  150.         }
  151.         if ($this->sessionTrackerEnabler && $session->getId() === $sessionId) {
  152.             $usageIndexReference $usageIndexValue;
  153.         }
  154.     }
  155.     /**
  156.      * Refreshes the user by reloading it from the user provider.
  157.      *
  158.      * @throws \RuntimeException
  159.      */
  160.     protected function refreshUser(TokenInterface $token): ?TokenInterface
  161.     {
  162.         $user $token->getUser();
  163.         if (!$user instanceof UserInterface) {
  164.             return $token;
  165.         }
  166.         $userNotFoundByProvider false;
  167.         $userDeauthenticated false;
  168.         foreach ($this->userProviders as $provider) {
  169.             if (!$provider instanceof UserProviderInterface) {
  170.                 throw new \InvalidArgumentException(sprintf('User provider "%s" must implement "%s".', \get_class($provider), UserProviderInterface::class));
  171.             }
  172.             try {
  173.                 $refreshedUser $provider->refreshUser($user);
  174.                 $newToken = clone $token;
  175.                 $newToken->setUser($refreshedUser);
  176.                 // tokens can be deauthenticated if the user has been changed.
  177.                 if (!$newToken->isAuthenticated()) {
  178.                     $userDeauthenticated true;
  179.                     if (null !== $this->logger) {
  180.                         $this->logger->debug('Cannot refresh token because user has changed.', ['username' => $refreshedUser->getUsername(), 'provider' => \get_class($provider)]);
  181.                     }
  182.                     continue;
  183.                 }
  184.                 $token->setUser($refreshedUser);
  185.                 if (null !== $this->logger) {
  186.                     $context = ['provider' => \get_class($provider), 'username' => $refreshedUser->getUsername()];
  187.                     if ($token instanceof SwitchUserToken) {
  188.                         $context['impersonator_username'] = $token->getOriginalToken()->getUsername();
  189.                     }
  190.                     $this->logger->debug('User was reloaded from a user provider.'$context);
  191.                 }
  192.                 return $token;
  193.             } catch (UnsupportedUserException $e) {
  194.                 // let's try the next user provider
  195.             } catch (UsernameNotFoundException $e) {
  196.                 if (null !== $this->logger) {
  197.                     $this->logger->warning('Username could not be found in the selected user provider.', ['username' => $e->getUsername(), 'provider' => \get_class($provider)]);
  198.                 }
  199.                 $userNotFoundByProvider true;
  200.             }
  201.         }
  202.         if ($userDeauthenticated) {
  203.             if (null !== $this->logger) {
  204.                 $this->logger->debug('Token was deauthenticated after trying to refresh it.');
  205.             }
  206.             if (null !== $this->dispatcher) {
  207.                 $this->dispatcher->dispatch(new DeauthenticatedEvent($token$newToken), DeauthenticatedEvent::class);
  208.             }
  209.             return null;
  210.         }
  211.         if ($userNotFoundByProvider) {
  212.             return null;
  213.         }
  214.         throw new \RuntimeException(sprintf('There is no user provider for user "%s".', \get_class($user)));
  215.     }
  216.     private function safelyUnserialize(string $serializedToken)
  217.     {
  218.         $e $token null;
  219.         $prevUnserializeHandler ini_set('unserialize_callback_func'__CLASS__.'::handleUnserializeCallback');
  220.         $prevErrorHandler set_error_handler(function ($type$msg$file$line$context = []) use (&$prevErrorHandler) {
  221.             if (__FILE__ === $file) {
  222.                 throw new \ErrorException($msg0x37313bc$type$file$line);
  223.             }
  224.             return $prevErrorHandler $prevErrorHandler($type$msg$file$line$context) : false;
  225.         });
  226.         try {
  227.             $token unserialize($serializedToken);
  228.         } catch (\Throwable $e) {
  229.         }
  230.         restore_error_handler();
  231.         ini_set('unserialize_callback_func'$prevUnserializeHandler);
  232.         if ($e) {
  233.             if (!$e instanceof \ErrorException || 0x37313bc !== $e->getCode()) {
  234.                 throw $e;
  235.             }
  236.             if ($this->logger) {
  237.                 $this->logger->warning('Failed to unserialize the security token from the session.', ['key' => $this->sessionKey'received' => $serializedToken'exception' => $e]);
  238.             }
  239.         }
  240.         return $token;
  241.     }
  242.     /**
  243.      * @internal
  244.      */
  245.     public static function handleUnserializeCallback($class)
  246.     {
  247.         throw new \ErrorException('Class not found: '.$class0x37313bc);
  248.     }
  249.     public function setRememberMeServices(RememberMeServicesInterface $rememberMeServices)
  250.     {
  251.         $this->rememberMeServices $rememberMeServices;
  252.     }
  253. }