我目前正在 Symfony (2+) 上编写自定义控制台命令。
我的命令调用一项服务,该服务使用具有依赖项注入(inject)的安全上下文(检查角色)。
为了在我的服务中进行安全检查,我想创建一个特定的用户并将该用户记录在我的控制台命令中。
我如何模拟该登录并在我的命令中具有可用的安全上下文?
我的服务检查:
if ($this->securityContext->getToken() == null ||
!$this->securityContext->isGranted('IS_AUTHENTICATED_FULLY')
)
我的命令是一个经典的控制台命令,它扩展了 ContainerAwareCommand
最好的问候,
最佳答案
您可以像这样在 Symfony2 中以编程方式对用户进行身份验证:
// create the authentication token
$token = new UsernamePasswordToken(
$user,
null,
'main',
$user->getRoles());
// give it to the security context
$this->container->get('security.context')->setToken($token);
根据评论编辑:
- 从 Symfony 2.6 开始,安全上下文已被弃用。改用这个:
$this->container->get('security.token_storage')->setToken($t oken);
感谢@andrea-sprega
关于php - Symfony - 在控制台命令中模拟登录和安全上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22606444/