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

2022-08-30 23:58:48

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

$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的上下文中提出的,但下面也有更新版本的答案。


答案 1

试试这个:

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

答案 2

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

security:
    always_authenticate_before_granting: true

推荐