我正在尝试编写一个需要访问用户权限级别的事件侦听器。在控制器中,我使用以下代码
代码:
$securityContext = $this->container->get('security.context');
if($securityContext->isGranted('ROLE_USER')){
//Do Something
}
但是在控制器之外我无法弄清楚如何获得安全上下文。可能吗?
答案 0 :(得分:20)
执行此操作的最佳方法是通过Service Container使用(如phpisuber所说)依赖注入。但是,您应该注入security.context
服务,而不是注入整个容器(这被认为是不好的做法,因为它会使您的整个类不易测试并且会破坏耦合):
acme_foo.bar_service:
class: %acme_foo.bar_service.class%
arguments:
- @security.context
您的服务可能是这样的:
<?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');
}
}
答案 1 :(得分:5)
有两种方法可以将其置于控制器之外:
依赖注入:
这是正确的方法,您只需要文档here。
mybundle.model.mymodel:
class: %mybundle.model.myclass%
arguments: [@servicecontainer]
快速和肮脏:
global $kernel;
$securityContext = $kernel->getContainer()->get('security.context');
答案 2 :(得分:0)
我知道这篇文章有点过时了,但它仍然是谷歌首批成果之一。
本文中的答案引用了SecurityContext
类,自Symfony 2.6起不再支持该类。由于课程弃用,这篇文章的接受答案是误导性的。
尝试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));
}
}