Search code examples
phpsymfonyfirewallrolesaccess-control

Bug Symfony2 isGranted('MY_ROLE') returns true but firewall returns 403


I'm dynamically adding a role to my user just after he logged in using an AuthenticationSuccessHandlerInterface listener.

public function onAuthenticationSuccess(Request $request, TokenInterface $token)
{
    $user = $this->security->getToken()->getUser();
    $user->addRole('MY_ROLE');

    var_dump($this->security->isGranted('MY_ROLE'));
    var_dump($this->security->getToken()->getRoles()); die;

    return new RedirectResponse('...');
}

Both var_dump() shows $user got the new right. I made User class implements EquatableInterface class and made an isEqualTo function in it to get my User data reloaded while I change it without needing any logout.

public function isEqualTo(UserInterface $user)
{
    return false;
}

But when my listener redirection is reached, I got an Access Denied in a white page without profiler on the page.

access_control:
    - { path: ^/login$, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/login/check$, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/register$, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/, roles: MY_ROLE }

I already tried setting in the class the role (in the code not dynamically), it works so it's my firewall seems working except for dynamically set data even if I reload the user.

Any idea about what's going wrong there?


Solution

  • I finally walked around the issue, using an event listener with security.interactive_login and kernel.request events.

    I set in session (in my action registered for the security.interactive_login event) a key and check in kernel.request event (catching each call to website) if the key is set to do one thing or an other.

    Hope this coulda help someone...