Symfony:如何从数据库中刷新经过身份验证的用户? [英] Symfony: How do I refresh the authenticated user from the database?

查看:25
本文介绍了Symfony:如何从数据库中刷新经过身份验证的用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Say for example I grant a new role to the currently authenticated user in a controller, like so:

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

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

在下一页加载时,当我再次获取经过身份验证的用户时:

On the next page load, when I grab the authenticated user again:

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

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

They are not granted the role. I am guessing this is because the user is stored in the session and needs to be refreshed.

我该怎么做?

如果这有所不同,我将使用 FOSUserBundle.

I am using FOSUserBundle if that makes a difference.

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

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 SymfonyComponentSecurityCoreAuthenticationTokenUsernamePasswordToken(
  $loggedInUser,
  null,
  'main',
  $loggedInUser->getRoles()
);

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

这篇关于Symfony:如何从数据库中刷新经过身份验证的用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆