When I do this in a controller:
$token = $this->get('security.context')->getToken();
The token is null if the controller is under an unprotected URL:
access_control:
- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/, roles: ROLE_ADMIN }
- { path: ^/public, roles: IS_AUTHENTICATED_ANONYMOUSLY }
In my case, the controller action is invoked on /public. The token exists if the code runs under / protected pages though.
The reason why I want this is because I want to include additional information in case the user is logged in, and I wanted to check for the existence of this “token”.
Is there a better way to check if the user has logged in — something that works in both protected and unprotected areas?
You can check if a user is authenticated by checking whether they are authenticated fully, that is, they are non-anonymous with the
isGrantedfunction.See here for more info.