DoppyNL
DoppyNL

Reputation: 1470

symfony2 getting the user provider from the service container

I need to get a user provider in a controller in Symfony2. I've got multiple user_providers, with 1 chain-provider chaining those.

There is a service defined in the container with the name security.user.provider.concrete.XXX (where XXX is what you specified in security.yml), but that service is marked as private.

I've managed to define an alias in the extension class of my bundle:

    $container->setAlias('my_bundle.user.provider', new Alias('security.user.provider.concrete.XXX')));

But I rather do it in a more nice way.

So, I got a couple of questions:

Upvotes: 1

Views: 1994

Answers (2)

DoppyNL
DoppyNL

Reputation: 1470

I've played with the configuration a little, and figured out how to generically create aliasses for any providers configured using a CompilerPass:

<?php
namespace MyBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class TestCompilerPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        $securityConfig = $container->getExtensionConfig('security');
        foreach ($securityConfig[0]['providers'] as $providerName => $providerConfig) {
            $container->setAlias('my_security.provider.' . $providerName, new Alias('security.user.provider.concrete.' . $providerName));
        }
    }
}

Add the following to your Bundle class:

public function build(ContainerBuilder $container) {
    // call parent
    parent::build($container);

    // run extra compilerPass
    $container->addCompilerPass(new TestCompilerPass());
}

This will create an alias for each UserProvider that is present. It will be available under the key: my_security.provider.XXX where XXX is the name configured in your security.yml.

I'm however unsure why the config is prepended with an array with key 0. I'm also not really sure if this is a good approach. If nothing better comes up I will be using this solution though.

Upvotes: 1

Reformat Code
Reformat Code

Reputation: 307

You can get a specific provider by the current loggedin users firewall name:

$token = $this->securityContext->getToken();
$providerKey = $token->getProviderKey(); // secured_area / firewall name

You can get see it here: https://codedump.io/share/unA0SxVxuP9v

Upvotes: 0

Related Questions