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

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