繁体   English   中英

Symfony:如何从数据库中刷新经过身份验证的用户?

[英]Symfony: How do I refresh the authenticated user from the database?

例如,我在控制器中为当前经过身份验证的用户授予一个新角色,如下所示:

$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();

他们没有被授予角色。 我猜这是因为用户存储在会话中并且需要刷新。

我该怎么做?

如果这有所作为,我将使用 FOSUserBundle。

编辑:这个问题最初是在 Symfony 2.3 版的上下文中提出的,但下面也有更新版本的答案。

试试这个:

$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);

不需要在上一个答案中重置令牌。 只需在您的安全配置文件(security.yml 等)中添加以下内容:

security:
    always_authenticate_before_granting: true

当一个答案被接受时,Symfony 实际上有一种本地方式来刷新 User 对象。 这篇文章要归功于 Joeri Timmermans。

刷新用户对象的步骤:

  1. 使您的 User 实体实现该接口

Symfony\\Component\\Security\\Core\\User\\EquatableInterface

  1. 实现抽象函数 isEqualTo:

 public function isEqualTo(UserInterface $user) { if ($user instanceof User) { // Check that the roles are the same, in any order $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; }

如果添加了任何新角色,上面的代码会刷新 User 对象。 同样的原则也适用于您比较的其他领域。

$user = $this->getUser();
$userManager = $this->get('fos_user.user_manager');
$user->addRole('ROLE_TEACHER');
$userManager->updateUser($user);
$newtoken = new \Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken($user,null,'main', $user->getRoles());
$token = $this->get('security.token_storage')->setToken($newtoken);

在 Symfony 4

public function somename(ObjectManager $om, TokenStorageInterface $ts)
    {
        $user = $this->getUser();
        if ($user) {
            $user->setRoles(['ROLE_VIP']); //change/update role
            // persist if need
            $om->flush();
            $ts->setToken(
                new PostAuthenticationGuardToken($user, 'main', $user->getRoles())
            );
            //...
        } else {
            //...
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM