vendor/symfony/security-bundle/DependencyInjection/SecurityExtension.php line 567

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\Bundle\SecurityBundle\DependencyInjection;
  11. use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\RememberMeFactory;
  12. use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\SecurityFactoryInterface;
  13. use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\UserProvider\UserProviderFactoryInterface;
  14. use Symfony\Bundle\SecurityBundle\SecurityUserValueResolver;
  15. use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
  16. use Symfony\Component\Config\FileLocator;
  17. use Symfony\Component\Console\Application;
  18. use Symfony\Component\DependencyInjection\Alias;
  19. use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
  20. use Symfony\Component\DependencyInjection\ChildDefinition;
  21. use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass;
  22. use Symfony\Component\DependencyInjection\ContainerBuilder;
  23. use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
  24. use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
  25. use Symfony\Component\DependencyInjection\Parameter;
  26. use Symfony\Component\DependencyInjection\Reference;
  27. use Symfony\Component\HttpKernel\DependencyInjection\Extension;
  28. use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
  29. use Symfony\Component\Security\Core\Encoder\Argon2iPasswordEncoder;
  30. use Symfony\Component\Security\Core\Encoder\NativePasswordEncoder;
  31. use Symfony\Component\Security\Core\Encoder\SodiumPasswordEncoder;
  32. use Symfony\Component\Security\Core\User\UserProviderInterface;
  33. use Symfony\Component\Security\Http\Controller\UserValueResolver;
  34. use Symfony\Component\Templating\Helper\Helper;
  35. use Twig\Extension\AbstractExtension;
  36. /**
  37.  * SecurityExtension.
  38.  *
  39.  * @author Fabien Potencier <[email protected]>
  40.  * @author Johannes M. Schmitt <[email protected]>
  41.  */
  42. class SecurityExtension extends Extension implements PrependExtensionInterface
  43. {
  44.     private $requestMatchers = [];
  45.     private $expressions = [];
  46.     private $contextListeners = [];
  47.     private $listenerPositions = ['pre_auth''form''http''remember_me'];
  48.     private $factories = [];
  49.     private $userProviderFactories = [];
  50.     private $statelessFirewallKeys = [];
  51.     public function __construct()
  52.     {
  53.         foreach ($this->listenerPositions as $position) {
  54.             $this->factories[$position] = [];
  55.         }
  56.     }
  57.     public function prepend(ContainerBuilder $container)
  58.     {
  59.         $rememberMeSecureDefault false;
  60.         $rememberMeSameSiteDefault null;
  61.         if (!isset($container->getExtensions()['framework'])) {
  62.             return;
  63.         }
  64.         foreach ($container->getExtensionConfig('framework') as $config) {
  65.             if (isset($config['session']) && \is_array($config['session'])) {
  66.                 $rememberMeSecureDefault $config['session']['cookie_secure'] ?? $rememberMeSecureDefault;
  67.                 $rememberMeSameSiteDefault = \array_key_exists('cookie_samesite'$config['session']) ? $config['session']['cookie_samesite'] : $rememberMeSameSiteDefault;
  68.             }
  69.         }
  70.         foreach ($this->listenerPositions as $position) {
  71.             foreach ($this->factories[$position] as $factory) {
  72.                 if ($factory instanceof RememberMeFactory) {
  73.                     \Closure::bind(function () use ($rememberMeSecureDefault$rememberMeSameSiteDefault) {
  74.                         $this->options['secure'] = $rememberMeSecureDefault;
  75.                         $this->options['samesite'] = $rememberMeSameSiteDefault;
  76.                     }, $factory$factory)();
  77.                 }
  78.             }
  79.         }
  80.     }
  81.     public function load(array $configsContainerBuilder $container)
  82.     {
  83.         if (!array_filter($configs)) {
  84.             return;
  85.         }
  86.         $mainConfig $this->getConfiguration($configs$container);
  87.         $config $this->processConfiguration($mainConfig$configs);
  88.         // load services
  89.         $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
  90.         $loader->load('security.xml');
  91.         $loader->load('security_listeners.xml');
  92.         $loader->load('security_rememberme.xml');
  93.         if (class_exists(Helper::class)) {
  94.             $loader->load('templating_php.xml');
  95.         }
  96.         if (class_exists(AbstractExtension::class)) {
  97.             $loader->load('templating_twig.xml');
  98.         }
  99.         $loader->load('collectors.xml');
  100.         $loader->load('guard.xml');
  101.         if ($container->hasParameter('kernel.debug') && $container->getParameter('kernel.debug')) {
  102.             $loader->load('security_debug.xml');
  103.         }
  104.         if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) {
  105.             $container->removeDefinition('security.expression_language');
  106.             $container->removeDefinition('security.access.expression_voter');
  107.         }
  108.         // set some global scalars
  109.         $container->setParameter('security.access.denied_url'$config['access_denied_url']);
  110.         $container->setParameter('security.authentication.manager.erase_credentials'$config['erase_credentials']);
  111.         $container->setParameter('security.authentication.session_strategy.strategy'$config['session_fixation_strategy']);
  112.         if (isset($config['access_decision_manager']['service'])) {
  113.             $container->setAlias('security.access.decision_manager'$config['access_decision_manager']['service'])->setPrivate(true);
  114.         } else {
  115.             $container
  116.                 ->getDefinition('security.access.decision_manager')
  117.                 ->addArgument($config['access_decision_manager']['strategy'])
  118.                 ->addArgument($config['access_decision_manager']['allow_if_all_abstain'])
  119.                 ->addArgument($config['access_decision_manager']['allow_if_equal_granted_denied']);
  120.         }
  121.         $container->setParameter('security.access.always_authenticate_before_granting'$config['always_authenticate_before_granting']);
  122.         $container->setParameter('security.authentication.hide_user_not_found'$config['hide_user_not_found']);
  123.         $this->createFirewalls($config$container);
  124.         $this->createAuthorization($config$container);
  125.         $this->createRoleHierarchy($config$container);
  126.         $container->getDefinition('security.authentication.guard_handler')
  127.             ->replaceArgument(2$this->statelessFirewallKeys);
  128.         if ($config['encoders']) {
  129.             $this->createEncoders($config['encoders'], $container);
  130.         }
  131.         if (class_exists(Application::class)) {
  132.             $loader->load('console.xml');
  133.             $container->getDefinition('security.command.user_password_encoder')->replaceArgument(1array_keys($config['encoders']));
  134.         }
  135.         if (!class_exists(UserValueResolver::class)) {
  136.             $container->getDefinition('security.user_value_resolver')->setClass(SecurityUserValueResolver::class);
  137.         }
  138.         $container->registerForAutoconfiguration(VoterInterface::class)
  139.             ->addTag('security.voter');
  140.     }
  141.     private function createRoleHierarchy(array $configContainerBuilder $container)
  142.     {
  143.         if (!isset($config['role_hierarchy']) || === \count($config['role_hierarchy'])) {
  144.             $container->removeDefinition('security.access.role_hierarchy_voter');
  145.             return;
  146.         }
  147.         $container->setParameter('security.role_hierarchy.roles'$config['role_hierarchy']);
  148.         $container->removeDefinition('security.access.simple_role_voter');
  149.     }
  150.     private function createAuthorization($configContainerBuilder $container)
  151.     {
  152.         foreach ($config['access_control'] as $access) {
  153.             $matcher $this->createRequestMatcher(
  154.                 $container,
  155.                 $access['path'],
  156.                 $access['host'],
  157.                 $access['port'],
  158.                 $access['methods'],
  159.                 $access['ips']
  160.             );
  161.             $attributes $access['roles'];
  162.             if ($access['allow_if']) {
  163.                 $attributes[] = $this->createExpression($container$access['allow_if']);
  164.             }
  165.             $container->getDefinition('security.access_map')
  166.                       ->addMethodCall('add', [$matcher$attributes$access['requires_channel']]);
  167.         }
  168.         // allow cache warm-up for expressions
  169.         if (\count($this->expressions)) {
  170.             $container->getDefinition('security.cache_warmer.expression')
  171.                 ->replaceArgument(0, new IteratorArgument(array_values($this->expressions)));
  172.         } else {
  173.             $container->removeDefinition('security.cache_warmer.expression');
  174.         }
  175.     }
  176.     private function createFirewalls($configContainerBuilder $container)
  177.     {
  178.         if (!isset($config['firewalls'])) {
  179.             return;
  180.         }
  181.         $firewalls $config['firewalls'];
  182.         $providerIds $this->createUserProviders($config$container);
  183.         // make the ContextListener aware of the configured user providers
  184.         $contextListenerDefinition $container->getDefinition('security.context_listener');
  185.         $arguments $contextListenerDefinition->getArguments();
  186.         $userProviders = [];
  187.         foreach ($providerIds as $userProviderId) {
  188.             $userProviders[] = new Reference($userProviderId);
  189.         }
  190.         $arguments[1] = new IteratorArgument($userProviders);
  191.         $contextListenerDefinition->setArguments($arguments);
  192.         if (=== \count($providerIds)) {
  193.             $container->setAlias(UserProviderInterface::class, current($providerIds));
  194.         }
  195.         $customUserChecker false;
  196.         // load firewall map
  197.         $mapDef $container->getDefinition('security.firewall.map');
  198.         $map $authenticationProviders $contextRefs = [];
  199.         foreach ($firewalls as $name => $firewall) {
  200.             if (isset($firewall['user_checker']) && 'security.user_checker' !== $firewall['user_checker']) {
  201.                 $customUserChecker true;
  202.             }
  203.             $configId 'security.firewall.map.config.'.$name;
  204.             list($matcher$listeners$exceptionListener$logoutListener) = $this->createFirewall($container$name$firewall$authenticationProviders$providerIds$configId);
  205.             $contextId 'security.firewall.map.context.'.$name;
  206.             $context $container->setDefinition($contextId, new ChildDefinition('security.firewall.context'));
  207.             $context
  208.                 ->replaceArgument(0, new IteratorArgument($listeners))
  209.                 ->replaceArgument(1$exceptionListener)
  210.                 ->replaceArgument(2$logoutListener)
  211.                 ->replaceArgument(3, new Reference($configId))
  212.             ;
  213.             $contextRefs[$contextId] = new Reference($contextId);
  214.             $map[$contextId] = $matcher;
  215.         }
  216.         $mapDef->replaceArgument(0ServiceLocatorTagPass::register($container$contextRefs));
  217.         $mapDef->replaceArgument(1, new IteratorArgument($map));
  218.         // add authentication providers to authentication manager
  219.         $authenticationProviders array_map(function ($id) {
  220.             return new Reference($id);
  221.         }, array_values(array_unique($authenticationProviders)));
  222.         $container
  223.             ->getDefinition('security.authentication.manager')
  224.             ->replaceArgument(0, new IteratorArgument($authenticationProviders))
  225.         ;
  226.         // register an autowire alias for the UserCheckerInterface if no custom user checker service is configured
  227.         if (!$customUserChecker) {
  228.             $container->setAlias('Symfony\Component\Security\Core\User\UserCheckerInterface', new Alias('security.user_checker'false));
  229.         }
  230.     }
  231.     private function createFirewall(ContainerBuilder $container$id$firewall, &$authenticationProviders$providerIds$configId)
  232.     {
  233.         $config $container->setDefinition($configId, new ChildDefinition('security.firewall.config'));
  234.         $config->replaceArgument(0$id);
  235.         $config->replaceArgument(1$firewall['user_checker']);
  236.         // Matcher
  237.         $matcher null;
  238.         if (isset($firewall['request_matcher'])) {
  239.             $matcher = new Reference($firewall['request_matcher']);
  240.         } elseif (isset($firewall['pattern']) || isset($firewall['host'])) {
  241.             $pattern = isset($firewall['pattern']) ? $firewall['pattern'] : null;
  242.             $host = isset($firewall['host']) ? $firewall['host'] : null;
  243.             $methods = isset($firewall['methods']) ? $firewall['methods'] : [];
  244.             $matcher $this->createRequestMatcher($container$pattern$hostnull$methods);
  245.         }
  246.         $config->replaceArgument(2$matcher ? (string) $matcher null);
  247.         $config->replaceArgument(3$firewall['security']);
  248.         // Security disabled?
  249.         if (false === $firewall['security']) {
  250.             return [$matcher, [], nullnull];
  251.         }
  252.         $config->replaceArgument(4$firewall['stateless']);
  253.         // Provider id (must be configured explicitly per firewall/authenticator if more than one provider is set)
  254.         $defaultProvider null;
  255.         if (isset($firewall['provider'])) {
  256.             if (!isset($providerIds[$normalizedName str_replace('-''_'$firewall['provider'])])) {
  257.                 throw new InvalidConfigurationException(sprintf('Invalid firewall "%s": user provider "%s" not found.'$id$firewall['provider']));
  258.             }
  259.             $defaultProvider $providerIds[$normalizedName];
  260.         } elseif (=== \count($providerIds)) {
  261.             $defaultProvider reset($providerIds);
  262.         }
  263.         $config->replaceArgument(5$defaultProvider);
  264.         // Register listeners
  265.         $listeners = [];
  266.         $listenerKeys = [];
  267.         // Channel listener
  268.         $listeners[] = new Reference('security.channel_listener');
  269.         $contextKey null;
  270.         // Context serializer listener
  271.         if (false === $firewall['stateless']) {
  272.             $contextKey $firewall['context'] ?? $id;
  273.             $listeners[] = new Reference($this->createContextListener($container$contextKey));
  274.             $sessionStrategyId 'security.authentication.session_strategy';
  275.         } else {
  276.             $this->statelessFirewallKeys[] = $id;
  277.             $sessionStrategyId 'security.authentication.session_strategy_noop';
  278.         }
  279.         $container->setAlias(new Alias('security.authentication.session_strategy.'.$idfalse), $sessionStrategyId);
  280.         $config->replaceArgument(6$contextKey);
  281.         // Logout listener
  282.         $logoutListenerId null;
  283.         if (isset($firewall['logout'])) {
  284.             $logoutListenerId 'security.logout_listener.'.$id;
  285.             $logoutListener $container->setDefinition($logoutListenerId, new ChildDefinition('security.logout_listener'));
  286.             $logoutListener->replaceArgument(3, [
  287.                 'csrf_parameter' => $firewall['logout']['csrf_parameter'],
  288.                 'csrf_token_id' => $firewall['logout']['csrf_token_id'],
  289.                 'logout_path' => $firewall['logout']['path'],
  290.             ]);
  291.             // add logout success handler
  292.             if (isset($firewall['logout']['success_handler'])) {
  293.                 $logoutSuccessHandlerId $firewall['logout']['success_handler'];
  294.             } else {
  295.                 $logoutSuccessHandlerId 'security.logout.success_handler.'.$id;
  296.                 $logoutSuccessHandler $container->setDefinition($logoutSuccessHandlerId, new ChildDefinition('security.logout.success_handler'));
  297.                 $logoutSuccessHandler->replaceArgument(1$firewall['logout']['target']);
  298.             }
  299.             $logoutListener->replaceArgument(2, new Reference($logoutSuccessHandlerId));
  300.             // add CSRF provider
  301.             if (isset($firewall['logout']['csrf_token_generator'])) {
  302.                 $logoutListener->addArgument(new Reference($firewall['logout']['csrf_token_generator']));
  303.             }
  304.             // add session logout handler
  305.             if (true === $firewall['logout']['invalidate_session'] && false === $firewall['stateless']) {
  306.                 $logoutListener->addMethodCall('addHandler', [new Reference('security.logout.handler.session')]);
  307.             }
  308.             // add cookie logout handler
  309.             if (\count($firewall['logout']['delete_cookies']) > 0) {
  310.                 $cookieHandlerId 'security.logout.handler.cookie_clearing.'.$id;
  311.                 $cookieHandler $container->setDefinition($cookieHandlerId, new ChildDefinition('security.logout.handler.cookie_clearing'));
  312.                 $cookieHandler->addArgument($firewall['logout']['delete_cookies']);
  313.                 $logoutListener->addMethodCall('addHandler', [new Reference($cookieHandlerId)]);
  314.             }
  315.             // add custom handlers
  316.             foreach ($firewall['logout']['handlers'] as $handlerId) {
  317.                 $logoutListener->addMethodCall('addHandler', [new Reference($handlerId)]);
  318.             }
  319.             // register with LogoutUrlGenerator
  320.             $container
  321.                 ->getDefinition('security.logout_url_generator')
  322.                 ->addMethodCall('registerListener', [
  323.                     $id,
  324.                     $firewall['logout']['path'],
  325.                     $firewall['logout']['csrf_token_id'],
  326.                     $firewall['logout']['csrf_parameter'],
  327.                     isset($firewall['logout']['csrf_token_generator']) ? new Reference($firewall['logout']['csrf_token_generator']) : null,
  328.                     false === $firewall['stateless'] && isset($firewall['context']) ? $firewall['context'] : null,
  329.                 ])
  330.             ;
  331.         }
  332.         // Determine default entry point
  333.         $configuredEntryPoint = isset($firewall['entry_point']) ? $firewall['entry_point'] : null;
  334.         // Authentication listeners
  335.         list($authListeners$defaultEntryPoint) = $this->createAuthenticationListeners($container$id$firewall$authenticationProviders$defaultProvider$providerIds$configuredEntryPoint);
  336.         $config->replaceArgument(7$configuredEntryPoint ?: $defaultEntryPoint);
  337.         $listeners array_merge($listeners$authListeners);
  338.         // Switch user listener
  339.         if (isset($firewall['switch_user'])) {
  340.             $listenerKeys[] = 'switch_user';
  341.             $listeners[] = new Reference($this->createSwitchUserListener($container$id$firewall['switch_user'], $defaultProvider$firewall['stateless'], $providerIds));
  342.         }
  343.         // Access listener
  344.         $listeners[] = new Reference('security.access_listener');
  345.         // Exception listener
  346.         $exceptionListener = new Reference($this->createExceptionListener($container$firewall$id$configuredEntryPoint ?: $defaultEntryPoint$firewall['stateless']));
  347.         $config->replaceArgument(8, isset($firewall['access_denied_handler']) ? $firewall['access_denied_handler'] : null);
  348.         $config->replaceArgument(9, isset($firewall['access_denied_url']) ? $firewall['access_denied_url'] : null);
  349.         $container->setAlias('security.user_checker.'.$id, new Alias($firewall['user_checker'], false));
  350.         foreach ($this->factories as $position) {
  351.             foreach ($position as $factory) {
  352.                 $key str_replace('-''_'$factory->getKey());
  353.                 if (\array_key_exists($key$firewall)) {
  354.                     $listenerKeys[] = $key;
  355.                 }
  356.             }
  357.         }
  358.         if (isset($firewall['anonymous'])) {
  359.             $listenerKeys[] = 'anonymous';
  360.         }
  361.         $config->replaceArgument(10$listenerKeys);
  362.         $config->replaceArgument(11, isset($firewall['switch_user']) ? $firewall['switch_user'] : null);
  363.         return [$matcher$listeners$exceptionListenernull !== $logoutListenerId ? new Reference($logoutListenerId) : null];
  364.     }
  365.     private function createContextListener($container$contextKey)
  366.     {
  367.         if (isset($this->contextListeners[$contextKey])) {
  368.             return $this->contextListeners[$contextKey];
  369.         }
  370.         $listenerId 'security.context_listener.'.\count($this->contextListeners);
  371.         $listener $container->setDefinition($listenerId, new ChildDefinition('security.context_listener'));
  372.         $listener->replaceArgument(2$contextKey);
  373.         return $this->contextListeners[$contextKey] = $listenerId;
  374.     }
  375.     private function createAuthenticationListeners($container$id$firewall, &$authenticationProviders$defaultProvider null, array $providerIds$defaultEntryPoint)
  376.     {
  377.         $listeners = [];
  378.         $hasListeners false;
  379.         foreach ($this->listenerPositions as $position) {
  380.             foreach ($this->factories[$position] as $factory) {
  381.                 $key str_replace('-''_'$factory->getKey());
  382.                 if (isset($firewall[$key])) {
  383.                     if (isset($firewall[$key]['provider'])) {
  384.                         if (!isset($providerIds[$normalizedName str_replace('-''_'$firewall[$key]['provider'])])) {
  385.                             throw new InvalidConfigurationException(sprintf('Invalid firewall "%s": user provider "%s" not found.'$id$firewall[$key]['provider']));
  386.                         }
  387.                         $userProvider $providerIds[$normalizedName];
  388.                     } elseif ('remember_me' === $key) {
  389.                         // RememberMeFactory will use the firewall secret when created
  390.                         $userProvider null;
  391.                     } elseif ($defaultProvider) {
  392.                         $userProvider $defaultProvider;
  393.                     } elseif (empty($providerIds)) {
  394.                         $userProvider sprintf('security.user.provider.missing.%s'$key);
  395.                         $container->setDefinition($userProvider, (new ChildDefinition('security.user.provider.missing'))->replaceArgument(0$id));
  396.                     } else {
  397.                         throw new InvalidConfigurationException(sprintf('Not configuring explicitly the provider for the "%s" listener on "%s" firewall is ambiguous as there is more than one registered provider.'$key$id));
  398.                     }
  399.                     list($provider$listenerId$defaultEntryPoint) = $factory->create($container$id$firewall[$key], $userProvider$defaultEntryPoint);
  400.                     $listeners[] = new Reference($listenerId);
  401.                     $authenticationProviders[] = $provider;
  402.                     $hasListeners true;
  403.                 }
  404.             }
  405.         }
  406.         // Anonymous
  407.         if (isset($firewall['anonymous'])) {
  408.             if (null === $firewall['anonymous']['secret']) {
  409.                 $firewall['anonymous']['secret'] = new Parameter('container.build_hash');
  410.             }
  411.             $listenerId 'security.authentication.listener.anonymous.'.$id;
  412.             $container
  413.                 ->setDefinition($listenerId, new ChildDefinition('security.authentication.listener.anonymous'))
  414.                 ->replaceArgument(1$firewall['anonymous']['secret'])
  415.             ;
  416.             $listeners[] = new Reference($listenerId);
  417.             $providerId 'security.authentication.provider.anonymous.'.$id;
  418.             $container
  419.                 ->setDefinition($providerId, new ChildDefinition('security.authentication.provider.anonymous'))
  420.                 ->replaceArgument(0$firewall['anonymous']['secret'])
  421.             ;
  422.             $authenticationProviders[] = $providerId;
  423.             $hasListeners true;
  424.         }
  425.         if (false === $hasListeners) {
  426.             throw new InvalidConfigurationException(sprintf('No authentication listener registered for firewall "%s".'$id));
  427.         }
  428.         return [$listeners$defaultEntryPoint];
  429.     }
  430.     private function createEncoders($encodersContainerBuilder $container)
  431.     {
  432.         $encoderMap = [];
  433.         foreach ($encoders as $class => $encoder) {
  434.             $encoderMap[$class] = $this->createEncoder($encoder$container);
  435.         }
  436.         $container
  437.             ->getDefinition('security.encoder_factory.generic')
  438.             ->setArguments([$encoderMap])
  439.         ;
  440.     }
  441.     private function createEncoder($configContainerBuilder $container)
  442.     {
  443.         // a custom encoder service
  444.         if (isset($config['id'])) {
  445.             return new Reference($config['id']);
  446.         }
  447.         // plaintext encoder
  448.         if ('plaintext' === $config['algorithm']) {
  449.             $arguments = [$config['ignore_case']];
  450.             return [
  451.                 'class' => 'Symfony\Component\Security\Core\Encoder\PlaintextPasswordEncoder',
  452.                 'arguments' => $arguments,
  453.             ];
  454.         }
  455.         // pbkdf2 encoder
  456.         if ('pbkdf2' === $config['algorithm']) {
  457.             return [
  458.                 'class' => 'Symfony\Component\Security\Core\Encoder\Pbkdf2PasswordEncoder',
  459.                 'arguments' => [
  460.                     $config['hash_algorithm'],
  461.                     $config['encode_as_base64'],
  462.                     $config['iterations'],
  463.                     $config['key_length'],
  464.                 ],
  465.             ];
  466.         }
  467.         // bcrypt encoder
  468.         if ('bcrypt' === $config['algorithm']) {
  469.             @trigger_error('Configuring an encoder with "bcrypt" as algorithm is deprecated since Symfony 4.3, use "auto" instead.'E_USER_DEPRECATED);
  470.             return [
  471.                 'class' => 'Symfony\Component\Security\Core\Encoder\BCryptPasswordEncoder',
  472.                 'arguments' => [$config['cost'] ?? 13],
  473.             ];
  474.         }
  475.         // Argon2i encoder
  476.         if ('argon2i' === $config['algorithm']) {
  477.             @trigger_error('Configuring an encoder with "argon2i" as algorithm is deprecated since Symfony 4.3, use "auto" instead.'E_USER_DEPRECATED);
  478.             if (!Argon2iPasswordEncoder::isSupported()) {
  479.                 if (\extension_loaded('sodium') && !\defined('SODIUM_CRYPTO_PWHASH_SALTBYTES')) {
  480.                     throw new InvalidConfigurationException('The installed libsodium version does not have support for Argon2i. Use "auto" instead.');
  481.                 }
  482.                 throw new InvalidConfigurationException('Argon2i algorithm is not supported. Install the libsodium extension or use "auto" instead.');
  483.             }
  484.             return [
  485.                 'class' => 'Symfony\Component\Security\Core\Encoder\Argon2iPasswordEncoder',
  486.                 'arguments' => [
  487.                     $config['memory_cost'],
  488.                     $config['time_cost'],
  489.                     $config['threads'],
  490.                 ],
  491.             ];
  492.         }
  493.         if ('native' === $config['algorithm']) {
  494.             return [
  495.                 'class' => NativePasswordEncoder::class,
  496.                 'arguments' => [
  497.                     $config['time_cost'],
  498.                     (($config['memory_cost'] ?? 0) << 10) ?: null,
  499.                     $config['cost'],
  500.                 ],
  501.             ];
  502.         }
  503.         if ('sodium' === $config['algorithm']) {
  504.             if (!SodiumPasswordEncoder::isSupported()) {
  505.                 throw new InvalidConfigurationException('Libsodium is not available. Install the sodium extension or use "auto" instead.');
  506.             }
  507.             return [
  508.                 'class' => SodiumPasswordEncoder::class,
  509.                 'arguments' => [
  510.                     $config['time_cost'],
  511.                     (($config['memory_cost'] ?? 0) << 10) ?: null,
  512.                 ],
  513.             ];
  514.         }
  515.         // run-time configured encoder
  516.         return $config;
  517.     }
  518.     // Parses user providers and returns an array of their ids
  519.     private function createUserProviders($configContainerBuilder $container)
  520.     {
  521.         $providerIds = [];
  522.         foreach ($config['providers'] as $name => $provider) {
  523.             $id $this->createUserDaoProvider($name$provider$container);
  524.             $providerIds[str_replace('-''_'$name)] = $id;
  525.         }
  526.         return $providerIds;
  527.     }
  528.     // Parses a <provider> tag and returns the id for the related user provider service
  529.     private function createUserDaoProvider($name$providerContainerBuilder $container)
  530.     {
  531.         $name $this->getUserProviderId($name);
  532.         // Doctrine Entity and In-memory DAO provider are managed by factories
  533.         foreach ($this->userProviderFactories as $factory) {
  534.             $key str_replace('-''_'$factory->getKey());
  535.             if (!empty($provider[$key])) {
  536.                 $factory->create($container$name$provider[$key]);
  537.                 return $name;
  538.             }
  539.         }
  540.         // Existing DAO service provider
  541.         if (isset($provider['id'])) {
  542.             $container->setAlias($name, new Alias($provider['id'], false));
  543.             return $provider['id'];
  544.         }
  545.         // Chain provider
  546.         if (isset($provider['chain'])) {
  547.             $providers = [];
  548.             foreach ($provider['chain']['providers'] as $providerName) {
  549.                 $providers[] = new Reference($this->getUserProviderId($providerName));
  550.             }
  551.             $container
  552.                 ->setDefinition($name, new ChildDefinition('security.user.provider.chain'))
  553.                 ->addArgument(new IteratorArgument($providers));
  554.             return $name;
  555.         }
  556.         throw new InvalidConfigurationException(sprintf('Unable to create definition for "%s" user provider'$name));
  557.     }
  558.     private function getUserProviderId($name)
  559.     {
  560.         return 'security.user.provider.concrete.'.strtolower($name);
  561.     }
  562.     private function createExceptionListener($container$config$id$defaultEntryPoint$stateless)
  563.     {
  564.         $exceptionListenerId 'security.exception_listener.'.$id;
  565.         $listener $container->setDefinition($exceptionListenerId, new ChildDefinition('security.exception_listener'));
  566.         $listener->replaceArgument(3$id);
  567.         $listener->replaceArgument(4null === $defaultEntryPoint null : new Reference($defaultEntryPoint));
  568.         $listener->replaceArgument(8$stateless);
  569.         // access denied handler setup
  570.         if (isset($config['access_denied_handler'])) {
  571.             $listener->replaceArgument(6, new Reference($config['access_denied_handler']));
  572.         } elseif (isset($config['access_denied_url'])) {
  573.             $listener->replaceArgument(5$config['access_denied_url']);
  574.         }
  575.         return $exceptionListenerId;
  576.     }
  577.     private function createSwitchUserListener($container$id$config$defaultProvider$stateless$providerIds)
  578.     {
  579.         $userProvider = isset($config['provider']) ? $this->getUserProviderId($config['provider']) : $defaultProvider;
  580.         if (!$userProvider) {
  581.             throw new InvalidConfigurationException(sprintf('Not configuring explicitly the provider for the "switch_user" listener on "%s" firewall is ambiguous as there is more than one registered provider.'$id));
  582.         }
  583.         $switchUserListenerId 'security.authentication.switchuser_listener.'.$id;
  584.         $listener $container->setDefinition($switchUserListenerId, new ChildDefinition('security.authentication.switchuser_listener'));
  585.         $listener->replaceArgument(1, new Reference($userProvider));
  586.         $listener->replaceArgument(2, new Reference('security.user_checker.'.$id));
  587.         $listener->replaceArgument(3$id);
  588.         $listener->replaceArgument(6$config['parameter']);
  589.         $listener->replaceArgument(7$config['role']);
  590.         $listener->replaceArgument(9$stateless ?: $config['stateless']);
  591.         return $switchUserListenerId;
  592.     }
  593.     private function createExpression($container$expression)
  594.     {
  595.         if (isset($this->expressions[$id '.security.expression.'.ContainerBuilder::hash($expression)])) {
  596.             return $this->expressions[$id];
  597.         }
  598.         if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) {
  599.             throw new \RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
  600.         }
  601.         $container
  602.             ->register($id'Symfony\Component\ExpressionLanguage\Expression')
  603.             ->setPublic(false)
  604.             ->addArgument($expression)
  605.         ;
  606.         return $this->expressions[$id] = new Reference($id);
  607.     }
  608.     private function createRequestMatcher(ContainerBuilder $container$path null$host nullint $port null$methods = [], array $ips null, array $attributes = [])
  609.     {
  610.         if ($methods) {
  611.             $methods array_map('strtoupper', (array) $methods);
  612.         }
  613.         if (null !== $ips) {
  614.             foreach ($ips as $ip) {
  615.                 $container->resolveEnvPlaceholders($ipnull$usedEnvs);
  616.                 if (!$usedEnvs && !$this->isValidIp($ip)) {
  617.                     throw new \LogicException(sprintf('The given value "%s" in the "security.access_control" config option is not a valid IP address.'$ip));
  618.                 }
  619.                 $usedEnvs null;
  620.             }
  621.         }
  622.         $id '.security.request_matcher.'.ContainerBuilder::hash([$path$host$port$methods$ips$attributes]);
  623.         if (isset($this->requestMatchers[$id])) {
  624.             return $this->requestMatchers[$id];
  625.         }
  626.         // only add arguments that are necessary
  627.         $arguments = [$path$host$methods$ips$attributesnull$port];
  628.         while (\count($arguments) > && !end($arguments)) {
  629.             array_pop($arguments);
  630.         }
  631.         $container
  632.             ->register($id'Symfony\Component\HttpFoundation\RequestMatcher')
  633.             ->setPublic(false)
  634.             ->setArguments($arguments)
  635.         ;
  636.         return $this->requestMatchers[$id] = new Reference($id);
  637.     }
  638.     public function addSecurityListenerFactory(SecurityFactoryInterface $factory)
  639.     {
  640.         $this->factories[$factory->getPosition()][] = $factory;
  641.     }
  642.     public function addUserProviderFactory(UserProviderFactoryInterface $factory)
  643.     {
  644.         $this->userProviderFactories[] = $factory;
  645.     }
  646.     /**
  647.      * Returns the base path for the XSD files.
  648.      *
  649.      * @return string The XSD base path
  650.      */
  651.     public function getXsdValidationBasePath()
  652.     {
  653.         return __DIR__.'/../Resources/config/schema';
  654.     }
  655.     public function getNamespace()
  656.     {
  657.         return 'http://symfony.com/schema/dic/security';
  658.     }
  659.     public function getConfiguration(array $configContainerBuilder $container)
  660.     {
  661.         // first assemble the factories
  662.         return new MainConfiguration($this->factories$this->userProviderFactories);
  663.     }
  664.     private function isValidIp(string $cidr): bool
  665.     {
  666.         $cidrParts explode('/'$cidr);
  667.         if (=== \count($cidrParts)) {
  668.             return false !== filter_var($cidrParts[0], FILTER_VALIDATE_IP);
  669.         }
  670.         $ip $cidrParts[0];
  671.         $netmask $cidrParts[1];
  672.         if (!ctype_digit($netmask)) {
  673.             return false;
  674.         }
  675.         if (filter_var($ipFILTER_VALIDATE_IPFILTER_FLAG_IPV4)) {
  676.             return $netmask <= 32;
  677.         }
  678.         if (filter_var($ipFILTER_VALIDATE_IPFILTER_FLAG_IPV6)) {
  679.             return $netmask <= 128;
  680.         }
  681.         return false;
  682.     }
  683. }