SecurityExtension.php 27 KB

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