Question

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.

Was it helpful?

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

OTHER TIPS

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)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top