vendor/symfony/security-bundle/DependencyInjection/SecurityExtension.php line375

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