/** * Append objects to global container. * * @param Pimple\Container $container */ public static function setupDependencyInjection(Container $container) { parent::setupDependencyInjection($container); /* * Prepare app firewall */ $requestMatcher = new RequestMatcher('^/rz-admin'); // allows configuration of different access control rules for specific parts of the website. $container['accessMap']->add($requestMatcher, [Role::ROLE_BACKEND_USER, Role::ROLE_SUPERADMIN]); /* * Listener */ $logoutListener = new LogoutListener($container['securityTokenStorage'], $container['httpUtils'], new DefaultLogoutSuccessHandler($container['httpUtils'], '/login'), ['logout_path' => '/rz-admin/logout']); //Symfony\Component\Security\Http\Logout\SessionLogoutHandler $logoutListener->addHandler(new SessionLogoutHandler()); $listeners = [$container['contextListener'], $logoutListener, new UsernamePasswordFormAuthenticationListener($container['securityTokenStorage'], $container['authentificationManager'], new SessionAuthenticationStrategy(SessionAuthenticationStrategy::MIGRATE), $container['httpUtils'], Kernel::SECURITY_DOMAIN, new AuthenticationSuccessHandler($container['httpUtils'], ['always_use_default_target_path' => false, 'default_target_path' => '/rz-admin', 'login_path' => '/login', 'target_path_parameter' => '_target_path', 'use_referer' => true]), new AuthenticationFailureHandler($container['httpKernel'], $container['httpUtils'], ['failure_path' => '/login', 'failure_forward' => false, 'login_path' => '/login', 'failure_path_parameter' => '_failure_path'], $container['logger']), ['check_path' => '/rz-admin/login_check'], $container['logger'], $container['dispatcher'], null), new AccessListener($container['securityTokenStorage'], $container['accessDecisionManager'], $container['accessMap'], $container['authentificationManager']), $container["switchUser"]]; $container['firewallMap']->add($requestMatcher, $listeners, $container['firewallExceptionListener']); }
function initSecurity(ContainerInterface $container, HttpKernel $kernel) { /** @var TokenStorage $tokenStorage */ /** @var UrlGenerator $urlGenerator */ /** @var UrlMatcher $urlMatcher */ /** @var EventDispatcherInterface $evenDispatcher */ /** @var AuthenticationProviderManager $authManager */ $tokenStorage = $container->get('token_storage'); $urlGenerator = $container->get('url_generator'); $urlMatcher = $container->get('url_matcher'); $evenDispatcher = $container->get('event_dispatcher'); $authManager = $container->get('security.authentication_provider_manager'); $trustResolver = new AuthenticationTrustResolver('Symfony\\Component\\Security\\Core\\Authentication\\Token\\AnonymousToken', 'Symfony\\Component\\Security\\Core\\Authentication\\Token\\RememberMeToken'); $httpUtils = new HttpUtils($urlGenerator, $urlMatcher); $voters = []; $roleHierarchy = new RoleHierarchy(['ROLE_ADMIN' => ['ROLE_USER']]); $voters[] = new RoleHierarchyVoter($roleHierarchy); $accessDecisionManager = new AccessDecisionManager($voters, AccessDecisionManager::STRATEGY_UNANIMOUS); $accessMap = new AccessMap(); $accessMap->add(new RequestMatcher('^/api/admin'), ['ROLE_ADMIN']); $accessMap->add(new RequestMatcher('^/api'), ['ROLE_USER']); $accessMap->add(new RequestMatcher('^/crud'), ['ROLE_USER']); $accessListener = new Firewall\AccessListener($tokenStorage, $accessDecisionManager, $accessMap, $authManager); $map = new FirewallMap(); $exceptionListener = new ExceptionListener($tokenStorage, $trustResolver, $httpUtils, 'exception_listener'); $map->add(new RequestMatcher('^/api'), [new Firewall\AnonymousAuthenticationListener($tokenStorage, 'anonymous_listener'), $container->get('security.api_authentication_listener'), $accessListener], $exceptionListener); $authEntryPoint = new FormAuthenticationEntryPoint($kernel, $httpUtils, '/login'); $exceptionListener = new ExceptionListener($tokenStorage, $trustResolver, $httpUtils, 'exception_listener', $authEntryPoint); $logoutListener = new Firewall\LogoutListener($tokenStorage, $httpUtils, new DefaultLogoutSuccessHandler($httpUtils, '/login')); $logoutListener->addHandler(new CookieClearingLogoutHandler(['remember_crud' => ['path' => '/', 'domain' => '']])); $map->add(new RequestMatcher('^/(login|logout)'), [new Firewall\AnonymousAuthenticationListener($tokenStorage, 'anonymous_listener'), getSimpleAuthFormListener($container, $kernel), $logoutListener, $accessListener], $exceptionListener); $rememberMeListener = new Firewall\RememberMeListener($tokenStorage, getRememberMeServices(), $authManager, null, $evenDispatcher); $map->add(new RequestMatcher('^/.+/crud'), [$rememberMeListener, $accessListener], $exceptionListener); $firewall = new Firewall($map, $evenDispatcher); $evenDispatcher->addListener(KernelEvents::REQUEST, [$firewall, 'onKernelRequest']); $evenDispatcher->addSubscriber(new ResponseListener()); }
public function register(Application $app) { // used to register routes for login_check and logout $this->fakeRoutes = array(); $that = $this; $app['security.role_hierarchy'] = array(); $app['security.access_rules'] = array(); $app['security'] = $app->share(function ($app) { return new SecurityContext($app['security.authentication_manager'], $app['security.access_manager']); }); $app['security.authentication_manager'] = $app->share(function ($app) { $manager = new AuthenticationProviderManager($app['security.authentication_providers']); $manager->setEventDispatcher($app['dispatcher']); return $manager; }); // by default, all users use the digest encoder $app['security.encoder_factory'] = $app->share(function ($app) { return new EncoderFactory(array('Symfony\\Component\\Security\\Core\\User\\UserInterface' => $app['security.encoder.digest'])); }); $app['security.encoder.digest'] = $app->share(function ($app) { return new MessageDigestPasswordEncoder(); }); $app['security.user_checker'] = $app->share(function ($app) { return new UserChecker(); }); $app['security.access_manager'] = $app->share(function ($app) { return new AccessDecisionManager($app['security.voters']); }); $app['security.voters'] = $app->share(function ($app) { return array(new RoleHierarchyVoter(new RoleHierarchy($app['security.role_hierarchy'])), new AuthenticatedVoter($app['security.trust_resolver'])); }); $app['security.firewall'] = $app->share(function ($app) { return new Firewall($app['security.firewall_map'], $app['dispatcher']); }); $app['security.channel_listener'] = $app->share(function ($app) { return new ChannelListener($app['security.access_map'], new RetryAuthenticationEntryPoint($app['request.http_port'], $app['request.https_port']), $app['logger']); }); // generate the build-in authentication factories foreach (array('logout', 'pre_auth', 'form', 'http', 'remember_me', 'anonymous') as $type) { $entryPoint = null; if ('http' === $type) { $entryPoint = 'http'; } elseif ('form' === $type) { $entryPoint = 'form'; } $app['security.authentication_listener.factory.' . $type] = $app->protect(function ($name, $options) use($type, $app, $entryPoint) { if ($entryPoint && !isset($app['security.entry_point.' . $name . '.' . $entryPoint])) { $app['security.entry_point.' . $name . '.' . $entryPoint] = $app['security.entry_point.' . $entryPoint . '._proto']($name, $options); } if (!isset($app['security.authentication_listener.' . $name . '.' . $type])) { $app['security.authentication_listener.' . $name . '.' . $type] = $app['security.authentication_listener.' . $type . '._proto']($name, $options); } $provider = 'anonymous' === $type ? 'anonymous' : 'dao'; if (!isset($app['security.authentication_provider.' . $name . '.' . $provider])) { $app['security.authentication_provider.' . $name . '.' . $provider] = $app['security.authentication_provider.' . $provider . '._proto']($name); } return array('security.authentication_provider.' . $name . '.' . $provider, 'security.authentication_listener.' . $name . '.' . $type, $entryPoint ? 'security.entry_point.' . $name . '.' . $entryPoint : null, $type); }); } $app['security.firewall_map'] = $app->share(function ($app) { $positions = array('logout', 'pre_auth', 'form', 'http', 'remember_me', 'anonymous'); $providers = array(); $configs = array(); foreach ($app['security.firewalls'] as $name => $firewall) { $entryPoint = null; $pattern = isset($firewall['pattern']) ? $firewall['pattern'] : null; $users = isset($firewall['users']) ? $firewall['users'] : array(); $security = isset($firewall['security']) ? (bool) $firewall['security'] : true; $stateless = isset($firewall['stateless']) ? (bool) $firewall['stateless'] : false; unset($firewall['pattern'], $firewall['users'], $firewall['security'], $firewall['stateless']); $protected = false === $security ? false : count($firewall); $listeners = array('security.channel_listener'); if ($protected) { if (!isset($app['security.context_listener.' . $name])) { if (!isset($app['security.user_provider.' . $name])) { $app['security.user_provider.' . $name] = is_array($users) ? $app['security.user_provider.inmemory._proto']($users) : $users; } $app['security.context_listener.' . $name] = $app['security.context_listener._proto']($name, array($app['security.user_provider.' . $name])); } if (false === $stateless) { $listeners[] = 'security.context_listener.' . $name; } $factories = array(); foreach ($positions as $position) { $factories[$position] = array(); } foreach ($firewall as $type => $options) { if ('switch_user' === $type) { continue; } // normalize options if (!is_array($options)) { if (!$options) { continue; } $options = array(); } if (!isset($app['security.authentication_listener.factory.' . $type])) { throw new \LogicException(sprintf('The "%s" authentication entry is not registered.', $type)); } list($providerId, $listenerId, $entryPointId, $position) = $app['security.authentication_listener.factory.' . $type]($name, $options); if (null !== $entryPointId) { $entryPoint = $entryPointId; } $factories[$position][] = $listenerId; $providers[] = $providerId; } foreach ($positions as $position) { foreach ($factories[$position] as $listener) { $listeners[] = $listener; } } $listeners[] = 'security.access_listener'; if (isset($firewall['switch_user'])) { $app['security.switch_user.' . $name] = $app['security.authentication_listener.switch_user._proto']($name, $firewall['switch_user']); $listeners[] = 'security.switch_user.' . $name; } if (!isset($app['security.exception_listener.' . $name])) { if (null == $entryPoint) { $app[$entryPoint = 'security.entry_point.' . $name . '.form'] = $app['security.entry_point.form._proto']($name, array()); } $app['security.exception_listener.' . $name] = $app['security.exception_listener._proto']($entryPoint, $name); } } $configs[$name] = array($pattern, $listeners, $protected); } $app['security.authentication_providers'] = array_map(function ($provider) use($app) { return $app[$provider]; }, array_unique($providers)); $map = new FirewallMap(); foreach ($configs as $name => $config) { $map->add(is_string($config[0]) ? new RequestMatcher($config[0]) : $config[0], array_map(function ($listenerId) use($app, $name) { $listener = $app[$listenerId]; if (isset($app['security.remember_me.service.' . $name])) { if ($listener instanceof AbstractAuthenticationListener) { $listener->setRememberMeServices($app['security.remember_me.service.' . $name]); } if ($listener instanceof LogoutListener) { $listener->addHandler($app['security.remember_me.service.' . $name]); } } return $listener; }, $config[1]), $config[2] ? $app['security.exception_listener.' . $name] : null); } return $map; }); $app['security.access_listener'] = $app->share(function ($app) { return new AccessListener($app['security'], $app['security.access_manager'], $app['security.access_map'], $app['security.authentication_manager'], $app['logger']); }); $app['security.access_map'] = $app->share(function ($app) { $map = new AccessMap(); foreach ($app['security.access_rules'] as $rule) { if (is_string($rule[0])) { $rule[0] = new RequestMatcher($rule[0]); } $map->add($rule[0], (array) $rule[1], isset($rule[2]) ? $rule[2] : null); } return $map; }); $app['security.trust_resolver'] = $app->share(function ($app) { return new AuthenticationTrustResolver('Symfony\\Component\\Security\\Core\\Authentication\\Token\\AnonymousToken', 'Symfony\\Component\\Security\\Core\\Authentication\\Token\\RememberMeToken'); }); $app['security.session_strategy'] = $app->share(function ($app) { return new SessionAuthenticationStrategy('migrate'); }); $app['security.http_utils'] = $app->share(function ($app) { return new HttpUtils(isset($app['url_generator']) ? $app['url_generator'] : null, $app['url_matcher']); }); $app['security.last_error'] = $app->protect(function (Request $request) { if ($request->attributes->has(SecurityContextInterface::AUTHENTICATION_ERROR)) { return $request->attributes->get(SecurityContextInterface::AUTHENTICATION_ERROR)->getMessage(); } $session = $request->getSession(); if ($session && $session->has(SecurityContextInterface::AUTHENTICATION_ERROR)) { $error = $session->get(SecurityContextInterface::AUTHENTICATION_ERROR)->getMessage(); $session->remove(SecurityContextInterface::AUTHENTICATION_ERROR); return $error; } }); // prototypes (used by the Firewall Map) $app['security.context_listener._proto'] = $app->protect(function ($providerKey, $userProviders) use($app) { return $app->share(function () use($app, $userProviders, $providerKey) { return new ContextListener($app['security'], $userProviders, $providerKey, $app['logger'], $app['dispatcher']); }); }); $app['security.user_provider.inmemory._proto'] = $app->protect(function ($params) use($app) { return $app->share(function () use($app, $params) { $users = array(); foreach ($params as $name => $user) { $users[$name] = array('roles' => (array) $user[0], 'password' => $user[1]); } return new InMemoryUserProvider($users); }); }); $app['security.exception_listener._proto'] = $app->protect(function ($entryPoint, $name) use($app) { return $app->share(function () use($app, $entryPoint, $name) { return new ExceptionListener($app['security'], $app['security.trust_resolver'], $app['security.http_utils'], $name, $app[$entryPoint], null, null, $app['logger']); }); }); $app['security.authentication.success_handler._proto'] = $app->protect(function ($name, $options) use($app) { return $app->share(function () use($name, $options, $app) { $handler = new DefaultAuthenticationSuccessHandler($app['security.http_utils'], $options); $handler->setProviderKey($name); return $handler; }); }); $app['security.authentication.failure_handler._proto'] = $app->protect(function ($name, $options) use($app) { return $app->share(function () use($name, $options, $app) { return new DefaultAuthenticationFailureHandler($app, $app['security.http_utils'], $options, $app['logger']); }); }); $app['security.authentication_listener.form._proto'] = $app->protect(function ($name, $options) use($app, $that) { return $app->share(function () use($app, $name, $options, $that) { $that->addFakeRoute('match', $tmp = isset($options['check_path']) ? $options['check_path'] : '/login_check', str_replace('/', '_', ltrim($tmp, '/'))); $class = isset($options['listener_class']) ? $options['listener_class'] : 'Symfony\\Component\\Security\\Http\\Firewall\\UsernamePasswordFormAuthenticationListener'; if (!isset($app['security.authentication.success_handler.' . $name])) { $app['security.authentication.success_handler.' . $name] = $app['security.authentication.success_handler._proto']($name, $options); } if (!isset($app['security.authentication.failure_handler.' . $name])) { $app['security.authentication.failure_handler.' . $name] = $app['security.authentication.failure_handler._proto']($name, $options); } return new $class($app['security'], $app['security.authentication_manager'], isset($app['security.session_strategy.' . $name]) ? $app['security.session_strategy.' . $name] : $app['security.session_strategy'], $app['security.http_utils'], $name, $app['security.authentication.success_handler.' . $name], $app['security.authentication.failure_handler.' . $name], $options, $app['logger'], $app['dispatcher'], isset($options['with_csrf']) && $options['with_csrf'] && isset($app['form.csrf_provider']) ? $app['form.csrf_provider'] : null); }); }); $app['security.authentication_listener.http._proto'] = $app->protect(function ($providerKey, $options) use($app) { return $app->share(function () use($app, $providerKey, $options) { return new BasicAuthenticationListener($app['security'], $app['security.authentication_manager'], $providerKey, $app['security.entry_point.' . $providerKey . '.http'], $app['logger']); }); }); $app['security.authentication_listener.anonymous._proto'] = $app->protect(function ($providerKey, $options) use($app) { return $app->share(function () use($app, $providerKey, $options) { return new AnonymousAuthenticationListener($app['security'], $providerKey, $app['logger']); }); }); $app['security.authentication.logout_handler._proto'] = $app->protect(function ($name, $options) use($app) { return $app->share(function () use($name, $options, $app) { return new DefaultLogoutSuccessHandler($app['security.http_utils'], isset($options['target_url']) ? $options['target_url'] : '/'); }); }); $app['security.authentication_listener.logout._proto'] = $app->protect(function ($name, $options) use($app, $that) { return $app->share(function () use($app, $name, $options, $that) { $that->addFakeRoute('get', $tmp = isset($options['logout_path']) ? $options['logout_path'] : '/logout', str_replace('/', '_', ltrim($tmp, '/'))); if (!isset($app['security.authentication.logout_handler.' . $name])) { $app['security.authentication.logout_handler.' . $name] = $app['security.authentication.logout_handler._proto']($name, $options); } $listener = new LogoutListener($app['security'], $app['security.http_utils'], $app['security.authentication.logout_handler.' . $name], $options, isset($options['with_csrf']) && $options['with_csrf'] && isset($app['form.csrf_provider']) ? $app['form.csrf_provider'] : null); $listener->addHandler(new SessionLogoutHandler()); return $listener; }); }); $app['security.authentication_listener.switch_user._proto'] = $app->protect(function ($name, $options) use($app, $that) { return $app->share(function () use($app, $name, $options, $that) { return new SwitchUserListener($app['security'], $app['security.user_provider.' . $name], $app['security.user_checker'], $name, $app['security.access_manager'], $app['logger'], isset($options['parameter']) ? $options['parameter'] : '_switch_user', isset($options['role']) ? $options['role'] : 'ROLE_ALLOWED_TO_SWITCH', $app['dispatcher']); }); }); $app['security.entry_point.form._proto'] = $app->protect(function ($name, array $options) use($app) { return $app->share(function () use($app, $options) { $loginPath = isset($options['login_path']) ? $options['login_path'] : '/login'; $useForward = isset($options['use_forward']) ? $options['use_forward'] : false; return new FormAuthenticationEntryPoint($app, $app['security.http_utils'], $loginPath, $useForward); }); }); $app['security.entry_point.http._proto'] = $app->protect(function ($name, array $options) use($app) { return $app->share(function () use($app, $name, $options) { return new BasicAuthenticationEntryPoint(isset($options['real_name']) ? $options['real_name'] : 'Secured'); }); }); $app['security.authentication_provider.dao._proto'] = $app->protect(function ($name) use($app) { return $app->share(function () use($app, $name) { return new DaoAuthenticationProvider($app['security.user_provider.' . $name], $app['security.user_checker'], $name, $app['security.encoder_factory']); }); }); $app['security.authentication_provider.anonymous._proto'] = $app->protect(function ($name) use($app) { return $app->share(function () use($app, $name) { return new AnonymousAuthenticationProvider($name); }); }); if (isset($app['validator'])) { $app['security.validator.user_password_validator'] = $app->share(function ($app) { // FIXME: in Symfony 2.2 Symfony\Component\Security\Core\Validator\Constraint // is replaced by Symfony\Component\Security\Core\Validator\Constraints if (class_exists('Symfony\\Component\\Security\\Core\\Validator\\Constraints\\UserPasswordValidator')) { return new UserPasswordValidator($app['security'], $app['security.encoder_factory']); } return new DeprecatedUserPasswordValidator($app['security'], $app['security.encoder_factory']); }); if (!isset($app['validator.validator_service_ids'])) { $app['validator.validator_service_ids'] = array(); } $app['validator.validator_service_ids'] = array_merge($app['validator.validator_service_ids'], array('security.validator.user_password' => 'security.validator.user_password_validator')); } }
public function register(Application $app) { // used to register routes for login_check and logout $this->fakeRoutes = array(); $that = $this; $app['security.role_hierarchy'] = array(); $app['security.access_rules'] = array(); $app['security'] = $app->share(function () use($app) { return new SecurityContext($app['security.authentication_manager'], $app['security.access_manager']); }); $app['security.authentication_manager'] = $app->share(function () use($app) { $manager = new AuthenticationProviderManager($app['security.authentication_providers']); $manager->setEventDispatcher($app['dispatcher']); return $manager; }); // by default, all users use the digest encoder $app['security.encoder_factory'] = $app->share(function () use($app) { return new EncoderFactory(array('Symfony\\Component\\Security\\Core\\User\\UserInterface' => $app['security.encoder.digest'])); }); $app['security.encoder.digest'] = $app->share(function () use($app) { return new MessageDigestPasswordEncoder(); }); $app['security.user_checker'] = $app->share(function () use($app) { return new UserChecker(); }); $app['security.access_manager'] = $app->share(function () use($app) { return new AccessDecisionManager($app['security.voters']); }); $app['security.voters'] = $app->share(function () use($app) { return array(new RoleHierarchyVoter(new RoleHierarchy($app['security.role_hierarchy'])), new AuthenticatedVoter($app['security.trust_resolver'])); }); $app['security.firewall'] = $app->share(function () use($app) { return new Firewall($app['security.firewall_map'], $app['dispatcher']); }); $app['security.channel_listener'] = $app->share(function () use($app) { return new ChannelListener($app['security.access_map'], new RetryAuthenticationEntryPoint($app['request.http_port'], $app['request.https_port']), $app['logger']); }); $app['security.firewall_map'] = $app->share(function () use($app) { $map = new FirewallMap(); $entryPoint = 'form'; foreach ($app['security.firewalls'] as $name => $firewall) { $pattern = isset($firewall['pattern']) ? $firewall['pattern'] : null; $users = isset($firewall['users']) ? $firewall['users'] : array(); unset($firewall['pattern'], $firewall['users']); $protected = count($firewall); $listeners = array($app['security.channel_listener']); if ($protected) { if (!isset($app['security.context_listener.' . $name])) { if (!isset($app['security.user_provider.' . $name])) { $app['security.user_provider.' . $name] = is_array($users) ? $app['security.user_provider.inmemory._proto']($users) : $users; } $app['security.context_listener.' . $name] = $app['security.context_listener._proto']($name, array($app['security.user_provider.' . $name])); } $listeners[] = $app['security.context_listener.' . $name]; } if (count($firewall)) { foreach (array('logout', 'pre_auth', 'form', 'http', 'remember_me', 'anonymous') as $type) { if (isset($firewall[$type])) { $options = $firewall[$type]; // normalize options if (!is_array($options)) { if (!$options) { continue; } $options = array(); } if ('http' == $type) { $entryPoint = 'http'; } if (!isset($app['security.authentication.' . $name . '.' . $type])) { if (!isset($app['security.entry_point.' . $entryPoint . '.' . $name])) { $app['security.entry_point.' . $entryPoint . '.' . $name] = $app['security.entry_point.' . $entryPoint . '._proto']($name); } $app['security.authentication.' . $name . '.' . $type] = $app['security.authentication.' . $type . '._proto']($name, $options); } $listeners[] = $app['security.authentication.' . $name . '.' . $type]; } } if ($protected) { $listeners[] = $app['security.access_listener']; if (isset($firewall['switch_user'])) { $listeners[] = $app['security.authentication.switch_user._proto']($name, $firewall['switch_user']); } } } if ($protected && !isset($app['security.exception_listener.' . $name])) { $app['security.exception_listener.' . $name] = $app['security.exception_listener._proto']($entryPoint, $name); } $map->add(is_string($pattern) ? new RequestMatcher($pattern) : $pattern, $listeners, $protected ? $app['security.exception_listener.' . $name] : null); } return $map; }); $app['security.authentication_providers'] = $app->share(function () use($app) { $providers = array(); foreach ($app['security.firewalls'] as $name => $firewall) { unset($firewall['pattern'], $firewall['users']); if (!count($firewall)) { continue; } if (!isset($app['security.authentication_provider.' . $name])) { $a = 'anonymous' == $name ? 'anonymous' : 'dao'; $app['security.authentication_provider.' . $name] = $app['security.authentication_provider.' . $a . '._proto']($name); } $providers[] = $app['security.authentication_provider.' . $name]; } return $providers; }); $app['security.access_listener'] = $app->share(function () use($app) { return new AccessListener($app['security'], $app['security.access_manager'], $app['security.access_map'], $app['security.authentication_manager'], $app['logger']); }); $app['security.access_map'] = $app->share(function () use($app) { $map = new AccessMap(); foreach ($app['security.access_rules'] as $rule) { if (is_string($rule[0])) { $rule[0] = new RequestMatcher($rule[0]); } $map->add($rule[0], (array) $rule[1], isset($rule[2]) ? $rule[2] : null); } return $map; }); $app['security.trust_resolver'] = $app->share(function () use($app) { return new AuthenticationTrustResolver('Symfony\\Component\\Security\\Core\\Authentication\\Token\\AnonymousToken', 'Symfony\\Component\\Security\\Core\\Authentication\\Token\\RememberMeToken'); }); $app['security.session_strategy'] = $app->share(function () use($app) { return new SessionAuthenticationStrategy('migrate'); }); $app['security.http_utils'] = $app->share(function () use($app) { return new HttpUtils(); }); $app['security.last_error'] = $app->protect(function (Request $request) { if ($request->attributes->has(SecurityContextInterface::AUTHENTICATION_ERROR)) { return $request->attributes->get(SecurityContextInterface::AUTHENTICATION_ERROR)->getMessage(); } $session = $request->getSession(); if ($session && $session->has(SecurityContextInterface::AUTHENTICATION_ERROR)) { $error = $session->get(SecurityContextInterface::AUTHENTICATION_ERROR)->getMessage(); $session->remove(SecurityContextInterface::AUTHENTICATION_ERROR); return $error; } }); // prototypes (used by the Firewall Map) $app['security.context_listener._proto'] = $app->protect(function ($providerKey, $userProviders) use($app) { return new ContextListener($app['security'], $userProviders, $providerKey, $app['logger'], $app['dispatcher']); }); $app['security.user_provider.inmemory._proto'] = $app->protect(function ($params) use($app) { $users = array(); foreach ($params as $name => $user) { $users[$name] = array('roles' => (array) $user[0], 'password' => $user[1]); } return new InMemoryUserProvider($users); }); $app['security.exception_listener._proto'] = $app->protect(function ($entryPoint, $name) use($app) { if (!isset($app['security.entry_point.' . $entryPoint . '.' . $name])) { $app['security.entry_point.' . $entryPoint . '.' . $name] = $app['security.entry_point.' . $entryPoint . '._proto']($name); } return new ExceptionListener($app['security'], $app['security.trust_resolver'], $app['security.http_utils'], $app['security.entry_point.' . $entryPoint . '.' . $name], null, null, $app['logger']); }); $app['security.authentication.form._proto'] = $app->protect(function ($providerKey, $options) use($app, $that) { $that->addFakeRoute(array('post', $tmp = isset($options['check_path']) ? $options['check_path'] : '/login_check', str_replace('/', '_', ltrim($tmp, '/')))); return new UsernamePasswordFormAuthenticationListener($app['security'], $app['security.authentication_manager'], $app['security.session_strategy'], $app['security.http_utils'], $providerKey, $options, null, null, $app['logger'], $app['dispatcher'], isset($options['with_csrf']) && $options['with_csrf'] && isset($app['form.csrf_provider']) ? $app['form.csrf_provider'] : null); }); $app['security.authentication.http._proto'] = $app->protect(function ($providerKey, $options) use($app) { return new BasicAuthenticationListener($app['security'], $app['security.authentication_manager'], $providerKey, $app['security.entry_point.http.' . $providerKey], $app['logger']); }); $app['security.authentication.anonymous._proto'] = $app->protect(function ($providerKey, $options) use($app) { return new AnonymousAuthenticationListener($app['security'], $providerKey, $app['logger']); }); $app['security.authentication.logout._proto'] = $app->protect(function ($providerKey, $options) use($app, $that) { $that->addFakeRoute(array('get', $tmp = isset($options['logout_path']) ? $options['logout_path'] : '/logout', str_replace('/', '_', ltrim($tmp, '/')))); $listener = new LogoutListener($app['security'], $app['security.http_utils'], $options, null, isset($options['with_csrf']) && $options['with_csrf'] && isset($app['form.csrf_provider']) ? $app['form.csrf_provider'] : null); $listener->addHandler(new SessionLogoutHandler()); return $listener; }); $app['security.authentication.switch_user._proto'] = $app->protect(function ($name, $options) use($app, $that) { return new SwitchUserListener($app['security'], $app['security.user_provider.' . $name], $app['security.user_checker'], $name, $app['security.access_manager'], $app['logger'], isset($options['parameter']) ? $options['parameter'] : '_switch_user', isset($options['role']) ? $options['role'] : 'ROLE_ALLOWED_TO_SWITCH', $app['dispatcher']); }); $app['security.entry_point.form._proto'] = $app->protect(function ($name, $loginPath = '/login', $useForward = false) use($app) { return new FormAuthenticationEntryPoint($app, $app['security.http_utils'], $loginPath, $useForward); }); $app['security.entry_point.http._proto'] = $app->protect(function ($name, $realName = 'Secured') use($app) { return new BasicAuthenticationEntryPoint($realName); }); $app['security.authentication_provider.dao._proto'] = $app->protect(function ($name) use($app) { return new DaoAuthenticationProvider($app['security.user_provider.' . $name], $app['security.user_checker'], $name, $app['security.encoder_factory']); }); $app['security.authentication_provider.anonymous._proto'] = $app->protect(function ($name) use($app) { return new AnonymousAuthenticationProvider($name); }); }
public function register(Container $app) { // used to register routes for login_check and logout $this->fakeRoutes = array(); $that = $this; $app['security.role_hierarchy'] = array(); $app['security.access_rules'] = array(); $app['security.hide_user_not_found'] = true; $app['security.encoder.bcrypt.cost'] = 13; $app['security.authorization_checker'] = function ($app) { return new AuthorizationChecker($app['security.token_storage'], $app['security.authentication_manager'], $app['security.access_manager']); }; $app['security.token_storage'] = function ($app) { return new TokenStorage(); }; $app['user'] = $app->factory(function ($app) { if (null === ($token = $app['security.token_storage']->getToken())) { return; } if (!is_object($user = $token->getUser())) { return; } return $user; }); $app['security.authentication_manager'] = function ($app) { $manager = new AuthenticationProviderManager($app['security.authentication_providers']); $manager->setEventDispatcher($app['dispatcher']); return $manager; }; // by default, all users use the digest encoder $app['security.encoder_factory'] = function ($app) { return new EncoderFactory(array('Symfony\\Component\\Security\\Core\\User\\UserInterface' => $app['security.default_encoder'])); }; // by default, all users use the BCrypt encoder $app['security.default_encoder'] = function ($app) { return $app['security.encoder.bcrypt']; }; $app['security.encoder.digest'] = function ($app) { return new MessageDigestPasswordEncoder(); }; $app['security.encoder.bcrypt'] = function ($app) { return new BCryptPasswordEncoder($app['security.encoder.bcrypt.cost']); }; $app['security.encoder.pbkdf2'] = function ($app) { return new Pbkdf2PasswordEncoder(); }; $app['security.user_checker'] = function ($app) { return new UserChecker(); }; $app['security.access_manager'] = function ($app) { return new AccessDecisionManager($app['security.voters']); }; $app['security.voters'] = function ($app) { return array(new RoleHierarchyVoter(new RoleHierarchy($app['security.role_hierarchy'])), new AuthenticatedVoter($app['security.trust_resolver'])); }; $app['security.firewall'] = function ($app) { return new Firewall($app['security.firewall_map'], $app['dispatcher']); }; $app['security.channel_listener'] = function ($app) { return new ChannelListener($app['security.access_map'], new RetryAuthenticationEntryPoint(isset($app['request.http_port']) ? $app['request.http_port'] : 80, isset($app['request.https_port']) ? $app['request.https_port'] : 443), $app['logger']); }; // generate the build-in authentication factories foreach (array('logout', 'pre_auth', 'guard', 'form', 'http', 'remember_me', 'anonymous') as $type) { $entryPoint = null; if ('http' === $type) { $entryPoint = 'http'; } elseif ('form' === $type) { $entryPoint = 'form'; } elseif ('guard' === $type) { $entryPoint = 'guard'; } $app['security.authentication_listener.factory.' . $type] = $app->protect(function ($name, $options) use($type, $app, $entryPoint) { if ($entryPoint && !isset($app['security.entry_point.' . $name . '.' . $entryPoint])) { $app['security.entry_point.' . $name . '.' . $entryPoint] = $app['security.entry_point.' . $entryPoint . '._proto']($name, $options); } if (!isset($app['security.authentication_listener.' . $name . '.' . $type])) { $app['security.authentication_listener.' . $name . '.' . $type] = $app['security.authentication_listener.' . $type . '._proto']($name, $options); } $provider = 'dao'; if ('anonymous' === $type) { $provider = 'anonymous'; } elseif ('guard' === $type) { $provider = 'guard'; } if (!isset($app['security.authentication_provider.' . $name . '.' . $provider])) { $app['security.authentication_provider.' . $name . '.' . $provider] = $app['security.authentication_provider.' . $provider . '._proto']($name, $options); } return array('security.authentication_provider.' . $name . '.' . $provider, 'security.authentication_listener.' . $name . '.' . $type, $entryPoint ? 'security.entry_point.' . $name . '.' . $entryPoint : null, $type); }); } $app['security.firewall_map'] = function ($app) { $positions = array('logout', 'pre_auth', 'guard', 'form', 'http', 'remember_me', 'anonymous'); $providers = array(); $configs = array(); foreach ($app['security.firewalls'] as $name => $firewall) { $entryPoint = null; $pattern = isset($firewall['pattern']) ? $firewall['pattern'] : null; $users = isset($firewall['users']) ? $firewall['users'] : array(); $security = isset($firewall['security']) ? (bool) $firewall['security'] : true; $stateless = isset($firewall['stateless']) ? (bool) $firewall['stateless'] : false; $context = isset($firewall['context']) ? $firewall['context'] : $name; unset($firewall['pattern'], $firewall['users'], $firewall['security'], $firewall['stateless'], $firewall['context']); $protected = false === $security ? false : count($firewall); $listeners = array('security.channel_listener'); if ($protected) { if (!isset($app['security.context_listener.' . $name])) { if (!isset($app['security.user_provider.' . $name])) { $app['security.user_provider.' . $name] = is_array($users) ? $app['security.user_provider.inmemory._proto']($users) : $users; } $app['security.context_listener.' . $name] = $app['security.context_listener._proto']($name, array($app['security.user_provider.' . $name])); } if (false === $stateless) { $listeners[] = 'security.context_listener.' . $context; } $factories = array(); foreach ($positions as $position) { $factories[$position] = array(); } foreach ($firewall as $type => $options) { if ('switch_user' === $type) { continue; } // normalize options if (!is_array($options)) { if (!$options) { continue; } $options = array(); } if (!isset($app['security.authentication_listener.factory.' . $type])) { throw new \LogicException(sprintf('The "%s" authentication entry is not registered.', $type)); } $options['stateless'] = $stateless; list($providerId, $listenerId, $entryPointId, $position) = $app['security.authentication_listener.factory.' . $type]($name, $options); if (null !== $entryPointId) { $entryPoint = $entryPointId; } $factories[$position][] = $listenerId; $providers[] = $providerId; } foreach ($positions as $position) { foreach ($factories[$position] as $listener) { $listeners[] = $listener; } } $listeners[] = 'security.access_listener'; if (isset($firewall['switch_user'])) { $app['security.switch_user.' . $name] = $app['security.authentication_listener.switch_user._proto']($name, $firewall['switch_user']); $listeners[] = 'security.switch_user.' . $name; } if (!isset($app['security.exception_listener.' . $name])) { if (null == $entryPoint) { $app[$entryPoint = 'security.entry_point.' . $name . '.form'] = $app['security.entry_point.form._proto']($name, array()); } $accessDeniedHandler = null; if (isset($app['security.access_denied_handler.' . $name])) { $accessDeniedHandler = $app['security.access_denied_handler.' . $name]; } $app['security.exception_listener.' . $name] = $app['security.exception_listener._proto']($entryPoint, $name, $accessDeniedHandler); } } $configs[$name] = array($pattern, $listeners, $protected); } $app['security.authentication_providers'] = array_map(function ($provider) use($app) { return $app[$provider]; }, array_unique($providers)); $map = new FirewallMap(); foreach ($configs as $name => $config) { $map->add(is_string($config[0]) ? new RequestMatcher($config[0]) : $config[0], array_map(function ($listenerId) use($app, $name) { $listener = $app[$listenerId]; if (isset($app['security.remember_me.service.' . $name])) { if ($listener instanceof AbstractAuthenticationListener || $listener instanceof GuardAuthenticationListener) { $listener->setRememberMeServices($app['security.remember_me.service.' . $name]); } if ($listener instanceof LogoutListener) { $listener->addHandler($app['security.remember_me.service.' . $name]); } } return $listener; }, $config[1]), $config[2] ? $app['security.exception_listener.' . $name] : null); } return $map; }; $app['security.access_listener'] = function ($app) { return new AccessListener($app['security.token_storage'], $app['security.access_manager'], $app['security.access_map'], $app['security.authentication_manager'], $app['logger']); }; $app['security.access_map'] = function ($app) { $map = new AccessMap(); foreach ($app['security.access_rules'] as $rule) { if (is_string($rule[0])) { $rule[0] = new RequestMatcher($rule[0]); } elseif (is_array($rule[0])) { $rule[0] += ['path' => null, 'host' => null, 'methods' => null, 'ips' => null, 'attributes' => array(), 'schemes' => null]; $rule[0] = new RequestMatcher($rule[0]['path'], $rule[0]['host'], $rule[0]['methods'], $rule[0]['ips'], $rule[0]['attributes'], $rule[0]['schemes']); } $map->add($rule[0], (array) $rule[1], isset($rule[2]) ? $rule[2] : null); } return $map; }; $app['security.trust_resolver'] = function ($app) { return new AuthenticationTrustResolver('Symfony\\Component\\Security\\Core\\Authentication\\Token\\AnonymousToken', 'Symfony\\Component\\Security\\Core\\Authentication\\Token\\RememberMeToken'); }; $app['security.session_strategy'] = function ($app) { return new SessionAuthenticationStrategy(SessionAuthenticationStrategy::MIGRATE); }; $app['security.http_utils'] = function ($app) { return new HttpUtils($app['url_generator'], $app['request_matcher']); }; $app['security.last_error'] = $app->protect(function (Request $request) { if ($request->attributes->has(Security::AUTHENTICATION_ERROR)) { return $request->attributes->get(Security::AUTHENTICATION_ERROR)->getMessage(); } $session = $request->getSession(); if ($session && $session->has(Security::AUTHENTICATION_ERROR)) { $message = $session->get(Security::AUTHENTICATION_ERROR)->getMessage(); $session->remove(Security::AUTHENTICATION_ERROR); return $message; } }); // prototypes (used by the Firewall Map) $app['security.context_listener._proto'] = $app->protect(function ($providerKey, $userProviders) use($app) { return function () use($app, $userProviders, $providerKey) { return new ContextListener($app['security.token_storage'], $userProviders, $providerKey, $app['logger'], $app['dispatcher']); }; }); $app['security.user_provider.inmemory._proto'] = $app->protect(function ($params) use($app) { return function () use($app, $params) { $users = array(); foreach ($params as $name => $user) { $users[$name] = array('roles' => (array) $user[0], 'password' => $user[1]); } return new InMemoryUserProvider($users); }; }); $app['security.exception_listener._proto'] = $app->protect(function ($entryPoint, $name, $accessDeniedHandler = null) use($app) { return function () use($app, $entryPoint, $name, $accessDeniedHandler) { return new ExceptionListener($app['security.token_storage'], $app['security.trust_resolver'], $app['security.http_utils'], $name, $app[$entryPoint], null, $accessDeniedHandler, $app['logger']); }; }); $app['security.authentication.success_handler._proto'] = $app->protect(function ($name, $options) use($app) { return function () use($name, $options, $app) { $handler = new DefaultAuthenticationSuccessHandler($app['security.http_utils'], $options); $handler->setProviderKey($name); return $handler; }; }); $app['security.authentication.failure_handler._proto'] = $app->protect(function ($name, $options) use($app) { return function () use($name, $options, $app) { return new DefaultAuthenticationFailureHandler($app, $app['security.http_utils'], $options, $app['logger']); }; }); $app['security.authentication_listener.guard._proto'] = $app->protect(function ($providerKey, $options) use($app, $that) { return function () use($app, $providerKey, $options, $that) { if (!isset($app['security.authentication.guard_handler'])) { $app['security.authentication.guard_handler'] = new GuardAuthenticatorHandler($app['security.token_storage'], $app['dispatcher']); } $authenticators = array(); foreach ($options['authenticators'] as $authenticatorId) { $authenticators[] = $app[$authenticatorId]; } return new GuardAuthenticationListener($app['security.authentication.guard_handler'], $app['security.authentication_manager'], $providerKey, $authenticators, $app['logger']); }; }); $app['security.authentication_listener.form._proto'] = $app->protect(function ($name, $options) use($app, $that) { return function () use($app, $name, $options, $that) { $that->addFakeRoute('match', $tmp = isset($options['check_path']) ? $options['check_path'] : '/login_check', str_replace('/', '_', ltrim($tmp, '/'))); $class = isset($options['listener_class']) ? $options['listener_class'] : 'Symfony\\Component\\Security\\Http\\Firewall\\UsernamePasswordFormAuthenticationListener'; if (!isset($app['security.authentication.success_handler.' . $name])) { $app['security.authentication.success_handler.' . $name] = $app['security.authentication.success_handler._proto']($name, $options); } if (!isset($app['security.authentication.failure_handler.' . $name])) { $app['security.authentication.failure_handler.' . $name] = $app['security.authentication.failure_handler._proto']($name, $options); } return new $class($app['security.token_storage'], $app['security.authentication_manager'], isset($app['security.session_strategy.' . $name]) ? $app['security.session_strategy.' . $name] : $app['security.session_strategy'], $app['security.http_utils'], $name, $app['security.authentication.success_handler.' . $name], $app['security.authentication.failure_handler.' . $name], $options, $app['logger'], $app['dispatcher'], isset($options['with_csrf']) && $options['with_csrf'] && isset($app['csrf.token_manager']) ? $app['csrf.token_manager'] : null); }; }); $app['security.authentication_listener.http._proto'] = $app->protect(function ($providerKey, $options) use($app) { return function () use($app, $providerKey, $options) { return new BasicAuthenticationListener($app['security.token_storage'], $app['security.authentication_manager'], $providerKey, $app['security.entry_point.' . $providerKey . '.http'], $app['logger']); }; }); $app['security.authentication_listener.anonymous._proto'] = $app->protect(function ($providerKey, $options) use($app) { return function () use($app, $providerKey, $options) { return new AnonymousAuthenticationListener($app['security.token_storage'], $providerKey, $app['logger']); }; }); $app['security.authentication.logout_handler._proto'] = $app->protect(function ($name, $options) use($app) { return function () use($name, $options, $app) { return new DefaultLogoutSuccessHandler($app['security.http_utils'], isset($options['target_url']) ? $options['target_url'] : '/'); }; }); $app['security.authentication_listener.logout._proto'] = $app->protect(function ($name, $options) use($app, $that) { return function () use($app, $name, $options, $that) { $that->addFakeRoute('get', $tmp = isset($options['logout_path']) ? $options['logout_path'] : '/logout', str_replace('/', '_', ltrim($tmp, '/'))); if (!isset($app['security.authentication.logout_handler.' . $name])) { $app['security.authentication.logout_handler.' . $name] = $app['security.authentication.logout_handler._proto']($name, $options); } $listener = new LogoutListener($app['security.token_storage'], $app['security.http_utils'], $app['security.authentication.logout_handler.' . $name], $options, isset($options['with_csrf']) && $options['with_csrf'] && isset($app['csrf.token_manager']) ? $app['csrf.token_manager'] : null); $invalidateSession = isset($options['invalidate_session']) ? $options['invalidate_session'] : true; if (true === $invalidateSession && false === $options['stateless']) { $listener->addHandler(new SessionLogoutHandler()); } return $listener; }; }); $app['security.authentication_listener.switch_user._proto'] = $app->protect(function ($name, $options) use($app, $that) { return function () use($app, $name, $options, $that) { return new SwitchUserListener($app['security.token_storage'], $app['security.user_provider.' . $name], $app['security.user_checker'], $name, $app['security.access_manager'], $app['logger'], isset($options['parameter']) ? $options['parameter'] : '_switch_user', isset($options['role']) ? $options['role'] : 'ROLE_ALLOWED_TO_SWITCH', $app['dispatcher']); }; }); $app['security.entry_point.form._proto'] = $app->protect(function ($name, array $options) use($app) { return function () use($app, $options) { $loginPath = isset($options['login_path']) ? $options['login_path'] : '/login'; $useForward = isset($options['use_forward']) ? $options['use_forward'] : false; return new FormAuthenticationEntryPoint($app, $app['security.http_utils'], $loginPath, $useForward); }; }); $app['security.entry_point.http._proto'] = $app->protect(function ($name, array $options) use($app) { return function () use($app, $name, $options) { return new BasicAuthenticationEntryPoint(isset($options['real_name']) ? $options['real_name'] : 'Secured'); }; }); $app['security.entry_point.guard._proto'] = $app->protect(function ($name, array $options) use($app) { if (isset($options['entry_point'])) { // if it's configured explicitly, use it! return $app[$options['entry_point']]; } $authenticatorIds = $options['authenticators']; if (count($authenticatorIds) == 1) { // if there is only one authenticator, use that as the entry point return $app[reset($authenticatorIds)]; } // we have multiple entry points - we must ask them to configure one throw new \LogicException(sprintf('Because you have multiple guard configurators, you need to set the "guard.entry_point" key to one of you configurators (%s)', implode(', ', $authenticatorIds))); }); $app['security.authentication_provider.dao._proto'] = $app->protect(function ($name, $options) use($app) { return function () use($app, $name) { return new DaoAuthenticationProvider($app['security.user_provider.' . $name], $app['security.user_checker'], $name, $app['security.encoder_factory'], $app['security.hide_user_not_found']); }; }); $app['security.authentication_provider.guard._proto'] = $app->protect(function ($name, $options) use($app) { return function () use($app, $name, $options) { $authenticators = array(); foreach ($options['authenticators'] as $authenticatorId) { $authenticators[] = $app[$authenticatorId]; } return new GuardAuthenticationProvider($authenticators, $app['security.user_provider.' . $name], $name, $app['security.user_checker']); }; }); $app['security.authentication_provider.anonymous._proto'] = $app->protect(function ($name, $options) use($app) { return function () use($app, $name) { return new AnonymousAuthenticationProvider($name); }; }); if (isset($app['validator'])) { $app['security.validator.user_password_validator'] = function ($app) { return new UserPasswordValidator($app['security.token_storage'], $app['security.encoder_factory']); }; $app['validator.validator_service_ids'] = array_merge($app['validator.validator_service_ids'], array('security.validator.user_password' => 'security.validator.user_password_validator')); } }