3

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.

Mohebifar
  • 3,341
  • 1
  • 24
  • 32
  • If you want to avoid logging out and back in, you have to manually update the session's token with the new role see https://stackoverflow.com/questions/15084054/symfony-2-1-7-update-security-token-setting-specific-roles-after-the-user-is-a – FuzzyTree May 13 '14 at 07:51

2 Answers2

2

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)

COil
  • 7,201
  • 2
  • 50
  • 98
0

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);
Mohebifar
  • 3,341
  • 1
  • 24
  • 32