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

查看:60
本文介绍了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 \Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken(
  $loggedInUser,
  null,
  'main',
  $loggedInUser->getRoles()
);

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

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

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