gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 00:19:29 26 4
gpt4 key购买 nike

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

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

他们未被授予该角色。我猜这是因为用户存储在 session 中,需要刷新。

我该怎么做?

如果有不同,我正在使用 FOSUserBundle。

EDIT: This question was originally asked in the context of Symfony version 2.3 but there are answers for more recent versions below as well.

最佳答案

试试这个:

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

关于php - Symfony:如何从数据库中刷新经过身份验证的用户?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19713802/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com