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

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$logoutListener) = $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$logoutListener)
  241.                 ->replaceArgument(3, new Reference($configId))
  242.             ;
  243.             $contextRefs[$contextId] = new Reference($contextId);
  244.             $map[$contextId] = $matcher;
  245.         }
  246.         $mapDef->replaceArgument(0ServiceLocatorTagPass::register($container$contextRefs));
  247.         $mapDef->replaceArgument(1, new IteratorArgument($map));
  248.         // add authentication providers to authentication manager
  249.         $authenticationProviders array_map(function ($id) {
  250.             return new Reference($id);
  251.         }, array_values(array_unique($authenticationProviders)));
  252.         $container
  253.             ->getDefinition('security.authentication.manager')
  254.             ->replaceArgument(0, new IteratorArgument($authenticationProviders))
  255.         ;
  256.         // register an autowire alias for the UserCheckerInterface if no custom user checker service is configured
  257.         if (!$customUserChecker) {
  258.             $container->setAlias('Symfony\Component\Security\Core\User\UserCheckerInterface', new Alias('security.user_checker'false));
  259.         }
  260.     }
  261.     private function createFirewall(ContainerBuilder $container$id$firewall, &$authenticationProviders$providerIds$configId)
  262.     {
  263.         $config $container->setDefinition($configId, new ChildDefinition('security.firewall.config'));
  264.         $config->replaceArgument(0$id);
  265.         $config->replaceArgument(1$firewall['user_checker']);
  266.         // Matcher
  267.         $matcher null;
  268.         if (isset($firewall['request_matcher'])) {
  269.             $matcher = new Reference($firewall['request_matcher']);
  270.         } elseif (isset($firewall['pattern']) || isset($firewall['host'])) {
  271.             $pattern = isset($firewall['pattern']) ? $firewall['pattern'] : null;
  272.             $host = isset($firewall['host']) ? $firewall['host'] : null;
  273.             $methods = isset($firewall['methods']) ? $firewall['methods'] : array();
  274.             $matcher $this->createRequestMatcher($container$pattern$host$methods);
  275.         }
  276.         $config->replaceArgument(2$matcher ? (string) $matcher null);
  277.         $config->replaceArgument(3$firewall['security']);
  278.         // Security disabled?
  279.         if (false === $firewall['security']) {
  280.             return array($matcher, array(), nullnull);
  281.         }
  282.         $config->replaceArgument(4$firewall['stateless']);
  283.         // Provider id (take the first registered provider if none defined)
  284.         $defaultProvider null;
  285.         if (isset($firewall['provider'])) {
  286.             if (!isset($providerIds[$normalizedName str_replace('-''_'$firewall['provider'])])) {
  287.                 throw new InvalidConfigurationException(sprintf('Invalid firewall "%s": user provider "%s" not found.'$id$firewall['provider']));
  288.             }
  289.             $defaultProvider $providerIds[$normalizedName];
  290.         } elseif (=== count($providerIds)) {
  291.             $defaultProvider reset($providerIds);
  292.         }
  293.         $config->replaceArgument(5$defaultProvider);
  294.         // Register listeners
  295.         $listeners = array();
  296.         $listenerKeys = array();
  297.         // Channel listener
  298.         $listeners[] = new Reference('security.channel_listener');
  299.         $contextKey null;
  300.         // Context serializer listener
  301.         if (false === $firewall['stateless']) {
  302.             $contextKey $id;
  303.             if (isset($firewall['context'])) {
  304.                 $contextKey $firewall['context'];
  305.             }
  306.             if (!$logoutOnUserChange $firewall['logout_on_user_change']) {
  307.                 @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);
  308.             }
  309.             if (isset($this->logoutOnUserChangeByContextKey[$contextKey]) && $this->logoutOnUserChangeByContextKey[$contextKey][1] !== $logoutOnUserChange) {
  310.                 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));
  311.             }
  312.             $this->logoutOnUserChangeByContextKey[$contextKey] = array($id$logoutOnUserChange);
  313.             $listeners[] = new Reference($this->createContextListener($container$contextKey$logoutOnUserChange));
  314.         }
  315.         $config->replaceArgument(6$contextKey);
  316.         // Logout listener
  317.         $logoutListenerId null;
  318.         if (isset($firewall['logout'])) {
  319.             $logoutListenerId 'security.logout_listener.'.$id;
  320.             $logoutListener $container->setDefinition($logoutListenerId, new ChildDefinition('security.logout_listener'));
  321.             $logoutListener->replaceArgument(3, array(
  322.                 'csrf_parameter' => $firewall['logout']['csrf_parameter'],
  323.                 'csrf_token_id' => $firewall['logout']['csrf_token_id'],
  324.                 'logout_path' => $firewall['logout']['path'],
  325.             ));
  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.             $logoutListener->replaceArgument(2, new Reference($logoutSuccessHandlerId));
  335.             // add CSRF provider
  336.             if (isset($firewall['logout']['csrf_token_generator'])) {
  337.                 $logoutListener->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.                 $logoutListener->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.                 $logoutListener->addMethodCall('addHandler', array(new Reference($cookieHandlerId)));
  349.             }
  350.             // add custom handlers
  351.             foreach ($firewall['logout']['handlers'] as $handlerId) {
  352.                 $logoutListener->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$exceptionListenernull !== $logoutListenerId ? new Reference($logoutListenerId) : null);
  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.                     } elseif ('remember_me' === $key) {
  425.                         // RememberMeFactory will use the firewall secret when created
  426.                         $userProvider null;
  427.                     } else {
  428.                         $userProvider $defaultProvider ?: $this->getFirstProvider($id$key$providerIds);
  429.                     }
  430.                     list($provider$listenerId$defaultEntryPoint) = $factory->create($container$id$firewall[$key], $userProvider$defaultEntryPoint);
  431.                     $listeners[] = new Reference($listenerId);
  432.                     $authenticationProviders[] = $provider;
  433.                     $hasListeners true;
  434.                 }
  435.             }
  436.         }
  437.         // Anonymous
  438.         if (isset($firewall['anonymous'])) {
  439.             if (null === $firewall['anonymous']['secret']) {
  440.                 $firewall['anonymous']['secret'] = new Parameter('container.build_hash');
  441.             }
  442.             $listenerId 'security.authentication.listener.anonymous.'.$id;
  443.             $container
  444.                 ->setDefinition($listenerId, new ChildDefinition('security.authentication.listener.anonymous'))
  445.                 ->replaceArgument(1$firewall['anonymous']['secret'])
  446.             ;
  447.             $listeners[] = new Reference($listenerId);
  448.             $providerId 'security.authentication.provider.anonymous.'.$id;
  449.             $container
  450.                 ->setDefinition($providerId, new ChildDefinition('security.authentication.provider.anonymous'))
  451.                 ->replaceArgument(0$firewall['anonymous']['secret'])
  452.             ;
  453.             $authenticationProviders[] = $providerId;
  454.             $hasListeners true;
  455.         }
  456.         if (false === $hasListeners) {
  457.             throw new InvalidConfigurationException(sprintf('No authentication listener registered for firewall "%s".'$id));
  458.         }
  459.         return array($listeners$defaultEntryPoint);
  460.     }
  461.     private function createEncoders($encodersContainerBuilder $container)
  462.     {
  463.         $encoderMap = array();
  464.         foreach ($encoders as $class => $encoder) {
  465.             $encoderMap[$class] = $this->createEncoder($encoder$container);
  466.         }
  467.         $container
  468.             ->getDefinition('security.encoder_factory.generic')
  469.             ->setArguments(array($encoderMap))
  470.         ;
  471.     }
  472.     private function createEncoder($configContainerBuilder $container)
  473.     {
  474.         // a custom encoder service
  475.         if (isset($config['id'])) {
  476.             return new Reference($config['id']);
  477.         }
  478.         // plaintext encoder
  479.         if ('plaintext' === $config['algorithm']) {
  480.             $arguments = array($config['ignore_case']);
  481.             return array(
  482.                 'class' => 'Symfony\Component\Security\Core\Encoder\PlaintextPasswordEncoder',
  483.                 'arguments' => $arguments,
  484.             );
  485.         }
  486.         // pbkdf2 encoder
  487.         if ('pbkdf2' === $config['algorithm']) {
  488.             return array(
  489.                 'class' => 'Symfony\Component\Security\Core\Encoder\Pbkdf2PasswordEncoder',
  490.                 'arguments' => array(
  491.                     $config['hash_algorithm'],
  492.                     $config['encode_as_base64'],
  493.                     $config['iterations'],
  494.                     $config['key_length'],
  495.                 ),
  496.             );
  497.         }
  498.         // bcrypt encoder
  499.         if ('bcrypt' === $config['algorithm']) {
  500.             return array(
  501.                 'class' => 'Symfony\Component\Security\Core\Encoder\BCryptPasswordEncoder',
  502.                 'arguments' => array($config['cost']),
  503.             );
  504.         }
  505.         // Argon2i encoder
  506.         if ('argon2i' === $config['algorithm']) {
  507.             if (!Argon2iPasswordEncoder::isSupported()) {
  508.                 throw new InvalidConfigurationException('Argon2i algorithm is not supported. Please install the libsodium extension or upgrade to PHP 7.2+.');
  509.             }
  510.             return array(
  511.                 'class' => 'Symfony\Component\Security\Core\Encoder\Argon2iPasswordEncoder',
  512.                 'arguments' => array(),
  513.             );
  514.         }
  515.         // run-time configured encoder
  516.         return $config;
  517.     }
  518.     // Parses user providers and returns an array of their ids
  519.     private function createUserProviders($configContainerBuilder $container)
  520.     {
  521.         $providerIds = array();
  522.         foreach ($config['providers'] as $name => $provider) {
  523.             $id $this->createUserDaoProvider($name$provider$container);
  524.             $providerIds[str_replace('-''_'$name)] = $id;
  525.         }
  526.         return $providerIds;
  527.     }
  528.     // Parses a <provider> tag and returns the id for the related user provider service
  529.     private function createUserDaoProvider($name$providerContainerBuilder $container)
  530.     {
  531.         $name $this->getUserProviderId($name);
  532.         // Doctrine Entity and In-memory DAO provider are managed by factories
  533.         foreach ($this->userProviderFactories as $factory) {
  534.             $key str_replace('-''_'$factory->getKey());
  535.             if (!empty($provider[$key])) {
  536.                 $factory->create($container$name$provider[$key]);
  537.                 return $name;
  538.             }
  539.         }
  540.         // Existing DAO service provider
  541.         if (isset($provider['id'])) {
  542.             $container->setAlias($name, new Alias($provider['id'], false));
  543.             return $provider['id'];
  544.         }
  545.         // Chain provider
  546.         if (isset($provider['chain'])) {
  547.             $providers = array();
  548.             foreach ($provider['chain']['providers'] as $providerName) {
  549.                 $providers[] = new Reference($this->getUserProviderId($providerName));
  550.             }
  551.             $container
  552.                 ->setDefinition($name, new ChildDefinition('security.user.provider.chain'))
  553.                 ->addArgument(new IteratorArgument($providers));
  554.             return $name;
  555.         }
  556.         throw new InvalidConfigurationException(sprintf('Unable to create definition for "%s" user provider'$name));
  557.     }
  558.     private function getUserProviderId($name)
  559.     {
  560.         return 'security.user.provider.concrete.'.strtolower($name);
  561.     }
  562.     private function createExceptionListener($container$config$id$defaultEntryPoint$stateless)
  563.     {
  564.         $exceptionListenerId 'security.exception_listener.'.$id;
  565.         $listener $container->setDefinition($exceptionListenerId, new ChildDefinition('security.exception_listener'));
  566.         $listener->replaceArgument(3$id);
  567.         $listener->replaceArgument(4null === $defaultEntryPoint null : new Reference($defaultEntryPoint));
  568.         $listener->replaceArgument(8$stateless);
  569.         // access denied handler setup
  570.         if (isset($config['access_denied_handler'])) {
  571.             $listener->replaceArgument(6, new Reference($config['access_denied_handler']));
  572.         } elseif (isset($config['access_denied_url'])) {
  573.             $listener->replaceArgument(5$config['access_denied_url']);
  574.         }
  575.         return $exceptionListenerId;
  576.     }
  577.     private function createSwitchUserListener($container$id$config$defaultProvider$stateless$providerIds)
  578.     {
  579.         $userProvider = isset($config['provider']) ? $this->getUserProviderId($config['provider']) : ($defaultProvider ?: $this->getFirstProvider($id'switch_user'$providerIds));
  580.         // in 4.0, ignore the `switch_user.stateless` key if $stateless is `true`
  581.         if ($stateless && false === $config['stateless']) {
  582.             @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);
  583.         }
  584.         $switchUserListenerId 'security.authentication.switchuser_listener.'.$id;
  585.         $listener $container->setDefinition($switchUserListenerId, new ChildDefinition('security.authentication.switchuser_listener'));
  586.         $listener->replaceArgument(1, new Reference($userProvider));
  587.         $listener->replaceArgument(2, new Reference('security.user_checker.'.$id));
  588.         $listener->replaceArgument(3$id);
  589.         $listener->replaceArgument(6$config['parameter']);
  590.         $listener->replaceArgument(7$config['role']);
  591.         $listener->replaceArgument(9$config['stateless']);
  592.         return $switchUserListenerId;
  593.     }
  594.     private function createExpression($container$expression)
  595.     {
  596.         if (isset($this->expressions[$id 'security.expression.'.ContainerBuilder::hash($expression)])) {
  597.             return $this->expressions[$id];
  598.         }
  599.         $container
  600.             ->register($id'Symfony\Component\ExpressionLanguage\SerializedParsedExpression')
  601.             ->setPublic(false)
  602.             ->addArgument($expression)
  603.             ->addArgument(serialize($this->getExpressionLanguage()->parse($expression, array('token''user''object''roles''request''trust_resolver'))->getNodes()))
  604.         ;
  605.         return $this->expressions[$id] = new Reference($id);
  606.     }
  607.     private function createRequestMatcher($container$path null$host null$methods = array(), $ip null, array $attributes = array())
  608.     {
  609.         if ($methods) {
  610.             $methods array_map('strtoupper', (array) $methods);
  611.         }
  612.         $id 'security.request_matcher.'.ContainerBuilder::hash(array($path$host$methods$ip$attributes));
  613.         if (isset($this->requestMatchers[$id])) {
  614.             return $this->requestMatchers[$id];
  615.         }
  616.         // only add arguments that are necessary
  617.         $arguments = array($path$host$methods$ip$attributes);
  618.         while (count($arguments) > && !end($arguments)) {
  619.             array_pop($arguments);
  620.         }
  621.         $container
  622.             ->register($id'Symfony\Component\HttpFoundation\RequestMatcher')
  623.             ->setPublic(false)
  624.             ->setArguments($arguments)
  625.         ;
  626.         return $this->requestMatchers[$id] = new Reference($id);
  627.     }
  628.     public function addSecurityListenerFactory(SecurityFactoryInterface $factory)
  629.     {
  630.         $this->factories[$factory->getPosition()][] = $factory;
  631.     }
  632.     public function addUserProviderFactory(UserProviderFactoryInterface $factory)
  633.     {
  634.         $this->userProviderFactories[] = $factory;
  635.     }
  636.     /**
  637.      * Returns the base path for the XSD files.
  638.      *
  639.      * @return string The XSD base path
  640.      */
  641.     public function getXsdValidationBasePath()
  642.     {
  643.         return __DIR__.'/../Resources/config/schema';
  644.     }
  645.     public function getNamespace()
  646.     {
  647.         return 'http://symfony.com/schema/dic/security';
  648.     }
  649.     public function getConfiguration(array $configContainerBuilder $container)
  650.     {
  651.         // first assemble the factories
  652.         return new MainConfiguration($this->factories$this->userProviderFactories);
  653.     }
  654.     private function getExpressionLanguage()
  655.     {
  656.         if (null === $this->expressionLanguage) {
  657.             if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) {
  658.                 throw new \RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
  659.             }
  660.             $this->expressionLanguage = new ExpressionLanguage();
  661.         }
  662.         return $this->expressionLanguage;
  663.     }
  664.     /**
  665.      * @deprecated since version 3.4, to be removed in 4.0
  666.      */
  667.     private function getFirstProvider($firewallName$listenerName, array $providerIds)
  668.     {
  669.         @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);
  670.         return $providerIds[$first];
  671.     }
  672. }