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

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\HttpKernel\Event\FilterResponseEvent;
  15. use Symfony\Component\HttpKernel\Event\RequestEvent;
  16. use Symfony\Component\HttpKernel\KernelEvents;
  17. use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolver;
  18. use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface;
  19. use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
  20. use Symfony\Component\Security\Core\Authentication\Token\RememberMeToken;
  21. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  22. use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
  23. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  24. use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
  25. use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
  26. use Symfony\Component\Security\Core\Role\SwitchUserRole;
  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. /**
  32.  * ContextListener manages the SecurityContext persistence through a session.
  33.  *
  34.  * @author Fabien Potencier <fabien@symfony.com>
  35.  * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  36.  *
  37.  * @final since Symfony 4.3
  38.  */
  39. class ContextListener implements ListenerInterface
  40. {
  41.     use LegacyListenerTrait;
  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.     /**
  51.      * @param iterable|UserProviderInterface[] $userProviders
  52.      */
  53.     public function __construct(TokenStorageInterface $tokenStorageiterable $userProvidersstring $contextKeyLoggerInterface $logger nullEventDispatcherInterface $dispatcher nullAuthenticationTrustResolverInterface $trustResolver null)
  54.     {
  55.         if (empty($contextKey)) {
  56.             throw new \InvalidArgumentException('$contextKey must not be empty.');
  57.         }
  58.         $this->tokenStorage $tokenStorage;
  59.         $this->userProviders $userProviders;
  60.         $this->sessionKey '_security_'.$contextKey;
  61.         $this->logger $logger;
  62.         $this->dispatcher LegacyEventDispatcherProxy::decorate($dispatcher);
  63.         $this->trustResolver $trustResolver ?: new AuthenticationTrustResolver(AnonymousToken::class, RememberMeToken::class);
  64.     }
  65.     /**
  66.      * Enables deauthentication during refreshUser when the user has changed.
  67.      *
  68.      * @param bool $logoutOnUserChange
  69.      *
  70.      * @deprecated since Symfony 4.1
  71.      */
  72.     public function setLogoutOnUserChange($logoutOnUserChange)
  73.     {
  74.         @trigger_error(sprintf('The "%s()" method is deprecated since Symfony 4.1.'__METHOD__), E_USER_DEPRECATED);
  75.     }
  76.     /**
  77.      * Reads the Security Token from the session.
  78.      */
  79.     public function __invoke(RequestEvent $event)
  80.     {
  81.         if (!$this->registered && null !== $this->dispatcher && $event->isMasterRequest()) {
  82.             $this->dispatcher->addListener(KernelEvents::RESPONSE, [$this'onKernelResponse']);
  83.             $this->registered true;
  84.         }
  85.         $request $event->getRequest();
  86.         $session $request->hasPreviousSession() ? $request->getSession() : null;
  87.         if (null === $session || null === $token $session->get($this->sessionKey)) {
  88.             $this->tokenStorage->setToken(null);
  89.             return;
  90.         }
  91.         $token $this->safelyUnserialize($token);
  92.         if (null !== $this->logger) {
  93.             $this->logger->debug('Read existing security token from the session.', [
  94.                 'key' => $this->sessionKey,
  95.                 'token_class' => \is_object($token) ? \get_class($token) : null,
  96.             ]);
  97.         }
  98.         if ($token instanceof TokenInterface) {
  99.             $token $this->refreshUser($token);
  100.             if (!$token && $this->rememberMeServices) {
  101.                 $this->rememberMeServices->loginFail($request);
  102.             }
  103.         } elseif (null !== $token) {
  104.             if (null !== $this->logger) {
  105.                 $this->logger->warning('Expected a security token from the session, got something else.', ['key' => $this->sessionKey'received' => $token]);
  106.             }
  107.             $token null;
  108.         }
  109.         $this->tokenStorage->setToken($token);
  110.     }
  111.     /**
  112.      * Writes the security token into the session.
  113.      */
  114.     public function onKernelResponse(FilterResponseEvent $event)
  115.     {
  116.         if (!$event->isMasterRequest()) {
  117.             return;
  118.         }
  119.         $request $event->getRequest();
  120.         if (!$request->hasSession()) {
  121.             return;
  122.         }
  123.         $this->dispatcher->removeListener(KernelEvents::RESPONSE, [$this'onKernelResponse']);
  124.         $this->registered false;
  125.         $session $request->getSession();
  126.         if ((null === $token $this->tokenStorage->getToken()) || $this->trustResolver->isAnonymous($token)) {
  127.             if ($request->hasPreviousSession()) {
  128.                 $session->remove($this->sessionKey);
  129.             }
  130.         } else {
  131.             $session->set($this->sessionKeyserialize($token));
  132.             if (null !== $this->logger) {
  133.                 $this->logger->debug('Stored the security token in the session.', ['key' => $this->sessionKey]);
  134.             }
  135.         }
  136.     }
  137.     /**
  138.      * Refreshes the user by reloading it from the user provider.
  139.      *
  140.      * @return TokenInterface|null
  141.      *
  142.      * @throws \RuntimeException
  143.      */
  144.     protected function refreshUser(TokenInterface $token)
  145.     {
  146.         $user $token->getUser();
  147.         if (!$user instanceof UserInterface) {
  148.             return $token;
  149.         }
  150.         $userNotFoundByProvider false;
  151.         $userDeauthenticated false;
  152.         foreach ($this->userProviders as $provider) {
  153.             if (!$provider instanceof UserProviderInterface) {
  154.                 throw new \InvalidArgumentException(sprintf('User provider "%s" must implement "%s".', \get_class($provider), UserProviderInterface::class));
  155.             }
  156.             try {
  157.                 $refreshedUser $provider->refreshUser($user);
  158.                 $newToken = clone $token;
  159.                 $newToken->setUser($refreshedUser);
  160.                 // tokens can be deauthenticated if the user has been changed.
  161.                 if (!$newToken->isAuthenticated()) {
  162.                     $userDeauthenticated true;
  163.                     if (null !== $this->logger) {
  164.                         $this->logger->debug('Cannot refresh token because user has changed.', ['username' => $refreshedUser->getUsername(), 'provider' => \get_class($provider)]);
  165.                     }
  166.                     continue;
  167.                 }
  168.                 $token->setUser($refreshedUser);
  169.                 if (null !== $this->logger) {
  170.                     $context = ['provider' => \get_class($provider), 'username' => $refreshedUser->getUsername()];
  171.                     if ($token instanceof SwitchUserToken) {
  172.                         $context['impersonator_username'] = $token->getOriginalToken()->getUsername();
  173.                     } else {
  174.                         foreach ($token->getRoles(false) as $role) {
  175.                             if ($role instanceof SwitchUserRole) {
  176.                                 $context['impersonator_username'] = $role->getSource(false)->getUsername();
  177.                                 break;
  178.                             }
  179.                         }
  180.                     }
  181.                     $this->logger->debug('User was reloaded from a user provider.'$context);
  182.                 }
  183.                 return $token;
  184.             } catch (UnsupportedUserException $e) {
  185.                 // let's try the next user provider
  186.             } catch (UsernameNotFoundException $e) {
  187.                 if (null !== $this->logger) {
  188.                     $this->logger->warning('Username could not be found in the selected user provider.', ['username' => $e->getUsername(), 'provider' => \get_class($provider)]);
  189.                 }
  190.                 $userNotFoundByProvider true;
  191.             }
  192.         }
  193.         if ($userDeauthenticated) {
  194.             if (null !== $this->logger) {
  195.                 $this->logger->debug('Token was deauthenticated after trying to refresh it.');
  196.             }
  197.             if (null !== $this->dispatcher) {
  198.                 $this->dispatcher->dispatch(new DeauthenticatedEvent($token$newToken), DeauthenticatedEvent::class);
  199.             }
  200.             return null;
  201.         }
  202.         if ($userNotFoundByProvider) {
  203.             return null;
  204.         }
  205.         throw new \RuntimeException(sprintf('There is no user provider for user "%s".', \get_class($user)));
  206.     }
  207.     private function safelyUnserialize($serializedToken)
  208.     {
  209.         $e $token null;
  210.         $prevUnserializeHandler ini_set('unserialize_callback_func'__CLASS__.'::handleUnserializeCallback');
  211.         $prevErrorHandler set_error_handler(function ($type$msg$file$line$context = []) use (&$prevErrorHandler) {
  212.             if (__FILE__ === $file) {
  213.                 throw new \ErrorException($msg0x37313bc$type$file$line);
  214.             }
  215.             return $prevErrorHandler $prevErrorHandler($type$msg$file$line$context) : false;
  216.         });
  217.         try {
  218.             $token unserialize($serializedToken);
  219.         } catch (\Throwable $e) {
  220.         }
  221.         restore_error_handler();
  222.         ini_set('unserialize_callback_func'$prevUnserializeHandler);
  223.         if ($e) {
  224.             if (!$e instanceof \ErrorException || 0x37313bc !== $e->getCode()) {
  225.                 throw $e;
  226.             }
  227.             if ($this->logger) {
  228.                 $this->logger->warning('Failed to unserialize the security token from the session.', ['key' => $this->sessionKey'received' => $serializedToken'exception' => $e]);
  229.             }
  230.         }
  231.         return $token;
  232.     }
  233.     /**
  234.      * @internal
  235.      */
  236.     public static function handleUnserializeCallback($class)
  237.     {
  238.         throw new \ErrorException('Class not found: '.$class0x37313bc);
  239.     }
  240.     public function setRememberMeServices(RememberMeServicesInterface $rememberMeServices)
  241.     {
  242.         $this->rememberMeServices $rememberMeServices;
  243.     }
  244. }