php - Symfony - 在控制台命令中模拟登录和安全上下文

标签 php symfony

我目前正在 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/

相关文章:

php - 如何关闭mysql连接?为什么它很重要?

php - 在 Laravel 中执行节点脚本

php - 如何使用vimeo高级API显示视频

php - Symfony FormBuilder - 附加元素的自定义选项?

php - 从 localhost 以外的其他地址访问 Symfony/web/config.php?

php - Laravel: Eloquent 'more than' 和 'lesser than'

php - 搜索结果中的 WordPress 面包屑

php - 如何连接 SQL 数据库和没有 SQL 数据库?

api - 配置 Silex 防火墙使用 api key 的正确方法

php - Symfony2 : Unknown MySQL server host