Symfony 2: get a security context outside the controller

I am trying to write an event listener that needs access to a user permission level. In the controller, I use the following code

Code:

$securityContext = $this->container->get('security.context'); if($securityContext->isGranted('ROLE_USER')){ //Do Something } 

But outside the controller, I cannot figure out how to get the security context. Is it possible?

+4
source share
3 answers

The best way to do this is to use (as phpisuber said) dependency injection through a service container . But instead of introducing the entire container (which is considered bad practice, as it makes your class less susceptible to testing and breaking the link), you should introduce the security.context service as follows:

 acme_foo.bar_service: class: %acme_foo.bar_service.class% arguments: - @security.context 

Your service might be something like this:

 <?php namespace Acme\FooBundle\Service; use Symfony\Component\Security\Core\SecurityContext; class BarService { /** * @var SecurityContext */ protected $context; /** * @param SecurityContext $context */ public function __construct($context) { $this->context = $context; } public function doSomething() { return $this->context->isGranted('ROLE_USER'); } } 
+20
source

There are two ways to get it outside the controller:

Dependency Injection:

This is the right way to do this, all you need is in the documentation here .

 mybundle.model.mymodel: class: %mybundle.model.myclass% arguments: [@servicecontainer] 

Quick and dirty:

 global $kernel; $securityContext = $kernel->getContainer()->get('security.context'); 
+5
source

I know this post is a bit outdated, but it was still one of the first results on Google.

The responses in this post refer to the SecurityContext class, which is no longer supported in Symfony 2.6. The accepted answer for this message is misleading due to class rejection.

Try this code from this answer :

 use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use YourNameSpace\UserBundle\Entity\User; class LoginController extends Controller{ public function registerAction() { $user = //Handle getting or creating the user entity likely with a posted form $token = new UsernamePasswordToken($user, null, 'main', $user->getRoles()); $this->get('security.token_storage')->setToken($token); $this->get('session')->set('_security_main', serialize($token)); } } 
0
source

All Articles