I read here how to check the login status of a user by inside a twig template for a Symfony2-based website.
However, I need to know how to check if the user is logged in from inside a controller. I was quite sure the the following code was right:
$user = $this->get('security.context')->getToken()->getUser();
but it always return something, e.g. a logged user or an anonymous user.
Any idea?
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:
Those roles represent three levels 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:
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.
Source: http://symfony.com/doc/2.3/cookbook/security/remember_me.html#forcing-the-user-to-re-authenticate-before-accessing-certain-resources