vendor/symfony/symfony/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php line 518

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