Friday, July 29, 2016

How to check if an user is logged in Symfony2 inside a controller?


106down voteaccepted
Warning: Checking for 'IS_AUTHENTICATED_FULLY' alone will return false if the user has logged in using "Remember me" functionality.
According to Symfony 2 documentation, there are 3 possibilities:
IS_AUTHENTICATED_ANONYMOUSLY - automatically assigned to a user who is in a firewall protected part of the site but who has not actually logged in. This is only possible if anonymous access has been allowed.
IS_AUTHENTICATED_REMEMBERED - automatically assigned to a user who was authenticated via a remember me cookie.
IS_AUTHENTICATED_FULLY - automatically assigned to a user that has provided their login details during the current session.
Those roles represent three levels of authentication:
If you have the IS_AUTHENTICATED_REMEMBERED role, then you also have the IS_AUTHENTICATED_ANONYMOUSLY role. If you have the IS_AUTHENTICATED_FULLY role, then you also have the other two roles. In other words, these roles represent three levels of increasing "strength" of authentication.
I ran into an issue where users of our system that had used "Remember Me" functionality were being treated as if they had not logged in at all on pages that only checked for 'IS_AUTHENTICATED_FULLY'.
The answer then is to require them to re-login if they are not authenticated fully, or to check for the remembered role:
$securityContext = $this->container->get('security.authorization_checker');
if ($securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
    // authenticated REMEMBERED, FULLY will imply REMEMBERED (NON anonymous)
}
Hopefully, this will save someone out there from making the same mistake I made. I used this very post as a reference when looking up how to check if someone was logged in or not on Symfony 2.

No comments:

Post a Comment