FOSUserBundle (用户切换角色)

在symfony中

例如我给予一个新的角色目前在一个控制器通过身份验证的用户,如下所示:

$em = $this->getDoctrine()->getManager();
$loggedInUser = $this->get('security.context')->getToken()->getUser();
$loggedInUser->addRole('ROLE_XYZ');

$em->persist($loggedInUser);
$em->flush();

在下一个页面加载,当我再次抓住身份验证的用户:

$loggedInUser = $this->get('security.context')->getToken()->getUser();

他们不是授予的角色。 我猜这是因为用户存储在会话中,需要刷新。

我怎么做呢?

一丶不需要令牌重置在前面的答案。 只是,在你的安全配置文件(security.yml等),添加:

security:
    always_authenticate_before_granting: true

也可以这么做

刷新用户对象的步骤

让你的用户实体实现的接口

使用abstract function isEqualTo:

public function isEqualTo(UserInterface $user)
{
    if ($user instanceof User) {
        // 检查角色是相同的
        $isEqual = count($this->getRoles()) == count($user->getRoles());
        if ($isEqual) {
            foreach($this->getRoles() as $role) {
                $isEqual = $isEqual && in_array($role, $user->getRoles());
            }
        }
        return $isEqual;
    }

    return false;
}

上面的代码刷新用户对象是否添加新角色。 同样的原则也适用于其他领域你比较。

原文链接 https://coderwall.com/p/nptn5q/how-to-reload-your-user-after-changes-in-symfony2

二丶重置一个令牌后切换角色

 

$em = $this->getDoctrine()->getManager();
$loggedInUser = $this->get('security.context')->getToken()->getUser();
$loggedInUser->addRole('ROLE_XYZ');

$em->persist($loggedInUser);
$em->flush();

$token = new \Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken(
  $loggedInUser,
  null,
  'main',
  $loggedInUser->getRoles()
);

$this->container->get('security.context')->setToken($token);

 

$loggedInUser = $this->get('security.context')->getToken()->getUser();
$loggedInUser->removeRole('ROLE_ABC');
$loggedInUser->addRole('ROLE_XYZ');

$token = new \Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken(
  $loggedInUser,
  null,
  'main',
  $loggedInUser->getRoles()
);

$this->container->get('security.context')->setToken($token);

 

posted on 2016-06-06 12:02  飞羽哥哥  阅读(963)  评论(0编辑  收藏  举报

导航