Update roles in security.context without need to logging in again

情到浓时终转凉″ 提交于 2019-12-10 09:54:22

问题


I use FOSUserBundle in my project. I have a Controller AcmeArticleBundle:Edit which has a route prefix /editor. And in my security.yml I added an access control.

access_control:
    - { path: ^/editor/, role: ROLE_EDITOR }

Now I add ROLE_EDITOR to a user in a controller. But user cannot access AcmeArticleBundle:Edit and security context does not change until logging out and logging in again.


回答1:


You can update the roles manually:

// YourController.php
$roles = $this->getToken()->getUser()->getRoles();
$roles[] = 'ROLE_NEW';
$this->getToken()->getUser()->setRoles($roles);
// Then persist your user entity or the new role will be lost at the next page call

(Code for Symfony2.0 but it should not be very different in 2.4)




回答2:


Finally I found the solution. I had to make a new security token and set it as security context.

$user = $this->getUser();
$user->addRole('ROLE_ADMIN');
$this->get('fos_user.user_manager')->updateUser($user);
$token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
$this->get('security.context')->setToken($token);


来源:https://stackoverflow.com/questions/23625137/update-roles-in-security-context-without-need-to-logging-in-again

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!