zoukankan      html  css  js  c++  java
  • 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 SymfonyComponentSecurityCoreAuthenticationTokenUsernamePasswordToken(
      $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 SymfonyComponentSecurityCoreAuthenticationTokenUsernamePasswordToken(
      $loggedInUser,
      null,
      'main',
      $loggedInUser->getRoles()
    );
    
    $this->container->get('security.context')->setToken($token);
  • 相关阅读:
    Java实现 LeetCode 413 等差数列划分
    Java实现 LeetCode 413 等差数列划分
    Java实现 LeetCode 412 Fizz Buzz
    简单字符设备驱动程序
    fork与vfork的区别
    进程创建函数fork()、vfork() ,以及excel()函数
    区分execl与system——应用程序中执行命令
    CMOS Sensor的调试经验分享
    嵌入式ARM-Linux开发工具下载地址合集
    嵌入式 linux 查看内存
  • 原文地址:https://www.cnblogs.com/g825482785/p/checkrole.html
Copyright © 2011-2022 走看看