Nad*_*urf 15 php symfony fosuserbundle
例如,我向控制器中当前经过身份验证的用户授予新角色,如下所示:
$em = $this->getDoctrine()->getManager();
$loggedInUser = $this->get('security.context')->getToken()->getUser();
$loggedInUser->addRole('ROLE_XYZ');
$em->persist($loggedInUser);
$em->flush();
Run Code Online (Sandbox Code Playgroud)
在下一页加载时,当我再次获取经过身份验证的用户时:
$loggedInUser = $this->get('security.context')->getToken()->getUser();
Run Code Online (Sandbox Code Playgroud)
他们没有被授予这个角色.我猜这是因为用户存储在会话中需要刷新.
我该怎么做呢?
如果有所作为,我正在使用FOSUserBundle.
dmn*_*ptr 23
试试这个:
$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);
Run Code Online (Sandbox Code Playgroud)
Mar*_*arc 13
在上一个答案中不需要重置令牌.只是,在您的安全配置文件(security.yml等等)中,添加以下内容:
security:
always_authenticate_before_granting: true
Run Code Online (Sandbox Code Playgroud)
Tho*_*son 13
虽然接受了答案,但Symfony实际上有一种刷新User对象的本机方式.本文将向Joeri Timmermans致谢.
刷新User对象的步骤:
Symfony的\分量\安全\核心\用户\ EquatableInterface
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;
}Run Code Online (Sandbox Code Playgroud)
如果添加了任何新角色,上面的代码将刷新User对象.对于您比较的其他领域,同样的原则也适用.
| 归档时间: |
|
| 查看次数: |
11542 次 |
| 最近记录: |