vendor/symfony/security/Http/Firewall/ContextListener.php line 38

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