Skip to content

Instantly share code, notes, and snippets.

@geerteltink
Created June 4, 2015 13:42
Show Gist options
  • Save geerteltink/40126eb27c6b635bd421 to your computer and use it in GitHub Desktop.
Save geerteltink/40126eb27c6b635bd421 to your computer and use it in GitHub Desktop.
Symfony 2 - Load security configuration depending on parameter
<?php
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Yaml\Yaml;
class AppKernel extends Kernel
{
public function registerBundles()
{
// ...
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
// Load common configuration except security.yml.
$loader->load($this->getRootDir().'/config/config_'.$this->getEnvironment().'.yml');
// Security has to be added in one go and can't be overwritten. So it has to be loaded after the common
// configuration and manipulated before injecting into the loader.
$loader->load(function (ContainerBuilder $container) {
// Load security configuration
$security = Yaml::parse(file_get_contents(
__DIR__.'/config/security.yml'
));
// Just make life easier
$security = $security['security'];
// Setup security configuration depending on the login type
// The configuration is not parsed yet, but we can access parameters set in parameters.yml.dist
switch ($container->getParameter('app_login_type')) {
case 'form_login':
unset($security['firewalls']['secured_area']['http_basic']);
unset($security['firewalls']['secured_area']['switch_user']);
unset($security['firewalls']['secured_area']['remote_user']);
break;
case 'shibboleth':
unset($security['firewalls']['login_firewall']);
unset($security['firewalls']['register_firewall']);
unset($security['firewalls']['secured_area']['anonymous']);
unset($security['firewalls']['secured_area']['http_basic']);
unset($security['firewalls']['secured_area']['switch_user']);
unset($security['firewalls']['secured_area']['form_login']);
break;
case 'dev':
// Do nothing, but make sure we can output an exception in case of a wrong parameter value
break;
default:
// Inform an invalid parameter value is found
throw new Exception('Invalid login type parameter.');
break;
}
// Inject the security configuration
$container->loadFromExtension('security', $security);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment