使用 Symfony 获取未登录用户的安全令牌 [英] Get security token for non-logged user with Symfony

查看:28
本文介绍了使用 Symfony 获取未登录用户的安全令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取任何用户的安全令牌,而不仅仅是当前登录的用户?

How can I get a security token for any user, not only the one currently logged in ?

我希望能够对从数据库中获取的用户调用 isGranted()

I would like to be able to call isGranted() on a user fetched from the database

推荐答案

isGranted() 来自安全服务,因此在不调整状态的情况下使用它来获取角色是困难的/不必要的会议.

isGranted() comes from the Security service, so it would be hard/unnecessary to use that to get Roles without adjusting the state of the session.

不要误会我的意思,这绝对有可能......这会起作用,例如:

Don't get me wrong, it's definitely possible... This would work, for example:

public function strangeAction()
{
    // Get your User, however you normally get it
    $user = $userRepository->find($id);
    // Save the current token so you can put it back later
    $previousToken = $this->get("security.context")->getToken();
    // Create a new token
    $token = new UsernamePasswordToken($user, null, "main", $user->getRoles());
    // Update the security context with the new token
    $this->get("security.context")->setToken($token);
    // Now you have access to isGranted()
    if ($this->get("security.context")->isGranted("ROLE_SOMETHING"))
    { /* Do something here */ }
    // Don't forget to reset the token!
    $this->get("security.context")->setToken($previousToken);
}

...但这真的毫无意义.

...but that really makes no sense.

实际上,您不需要令牌.一个更好的方法是在你的 User 实体中添加一个 isGranted() 方法:

In reality, you don't need the token. A much better way of doing this would be to add an isGranted() method into your User entity:

// Namespace\YourBundle\Entity\User.php

class User
{
    ...
    public function isGranted($role)
    {
    return in_array($role, $this->getRoles());
    }
    ...
}

现在您可以在控制器中获取这些角色:

Now you can get those roles in your controllers:

public function notSoStrangeAction()
{
    // Get your User, however you normally get it
    $user = $userRepository->find($id);
    // Find out if that User has a Role associated to it
    if ($user->isGranted("ROLE_SOMETHING"))
    { /* Do something here */ }
}

这篇关于使用 Symfony 获取未登录用户的安全令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆