使用Symfony获取未登录用户的安全令牌

Maë*_*son 3 php symfony

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

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

Tho*_*ley 5

isGranted() 来自安全服务,因此很难/没有必要使用它来获取角色而不调整会话状态.

不要误会我的意思,这绝对是可能的......这样可行,例如:

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);
}
Run Code Online (Sandbox Code Playgroud)

......但这真的没有意义.

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

// Namespace\YourBundle\Entity\User.php

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

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

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 */ }
}
Run Code Online (Sandbox Code Playgroud)

  • 这个提议的问题在于它不依赖于 security.yml 中定义的角色层次结构。查找用户是否具有角色 A 与查找用户是否被授予角色(考虑角色层次结构)不同。后者更难。我正在寻找这样的解决方案...... (2认同)