简体   繁体   English

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

[英]Symfony: How do I refresh the authenticated user from the database?

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.我猜这是因为用户存储在会话中并且需要刷新。

How do I do this?我该怎么做?

I am using FOSUserBundle if that makes a difference.如果这有所作为,我将使用 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.编辑:这个问题最初是在 Symfony 2.3 版的上下文中提出的,但下面也有更新版本的答案。

Try this:试试这个:

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

There's no need for the token reset in the previous answer.不需要在上一个答案中重置令牌。 Just, in your security config file (security.yml, etc...), add this:只需在您的安全配置文件(security.yml 等)中添加以下内容:

security:
    always_authenticate_before_granting: true

While an answer is accepted, Symfony actually has a native way to refresh the User object.当一个答案被接受时,Symfony 实际上有一种本地方式来刷新 User 对象。 Credit goes out to Joeri Timmermans for this article . 这篇文章要归功于 Joeri Timmermans。

Steps for refreshing the User object:刷新用户对象的步骤:

  1. Make your User entity implement the interface使您的 User 实体实现该接口

Symfony\\Component\\Security\\Core\\User\\EquatableInterface Symfony\\Component\\Security\\Core\\User\\EquatableInterface

  1. Implement the abstract function isEqualTo:实现抽象函数 isEqualTo:

 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; }

The code above refreshes the User object if any new roles are added.如果添加了任何新角色,上面的代码会刷新 User 对象。 The same principle also holds true for other fields you compare.同样的原则也适用于您比较的其他领域。

$user = $this->getUser();
$userManager = $this->get('fos_user.user_manager');
$user->addRole('ROLE_TEACHER');
$userManager->updateUser($user);
$newtoken = new \Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken($user,null,'main', $user->getRoles());
$token = $this->get('security.token_storage')->setToken($newtoken);

In Symfony 4在 Symfony 4

public function somename(ObjectManager $om, TokenStorageInterface $ts)
    {
        $user = $this->getUser();
        if ($user) {
            $user->setRoles(['ROLE_VIP']); //change/update role
            // persist if need
            $om->flush();
            $ts->setToken(
                new PostAuthenticationGuardToken($user, 'main', $user->getRoles())
            );
            //...
        } else {
            //...
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何缓存当前经过身份验证的用户? - How do I cache the current authenticated user? 从上下文Symfony中删除经过身份验证的用户 - Remove authenticated user from context Symfony 如何将硬编码用户ID更改为已认证的用户? - How do I change the hard code user id into the authenticated user? 在从文件系统公用磁盘访问/查看文件之前,如何检查用户是否已通过身份验证? - How do I check whether a user is authenticated before accessing/viewing a file from the filesystem public disk? Symfony检查用户是否已通过身份验证 - Symfony check if user is authenticated Symfony2获取当前经过身份验证的数据库用户凭据 - Symfony2 get current authenticated database user credentials 我如何获得在Zend Framework 2中针对用户进行身份验证的BaseDn - How do I get the BaseDn the user is authenticated against in Zend Framework 2 Symfony:在使用API​​密钥进行身份验证时,如何注销当前用户(如果已通过身份验证且不相同)? - Symfony: on authentication with API Keys how do logout the current user (if already authenticated and not the same)? Symfony 安全性:当用户从会话中进行身份验证时是否存在事件? - Symfony security: Is there an event when a user is authenticated from the session? Symfony 2注销,用户仍通过身份验证 - Symfony 2 Logout, user still authenticated
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM