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

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