Reputation: 123
I would like to do a check if user is authenticated inside a controller in Symfony 4. Based on the check, I want to download different data from database to display to anonymous and to authenticated users.
My first reaction was to to get user object and check if it is null or not, but according to the manual: https://symfony.com/doc/current/security.html#denying-access-roles-and-other-authorization it is a no-no:
The point is this: always check to see if the user is logged in before using the User object, and use the isGranted() method (or access_control) to do this:
// yay! Use this to see if the user is logged in $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
// boo :(. Never check for the User object to see if they're logged in if ($this->getUser()) { // ... }
I cannot use $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY'); since I do not want to deny access to anonymous users either, I just want to load a different set of data for them.
So how to check if the user is authenticated without denying the access?
Upvotes: 0
Views: 2652
Reputation: 411
As stated in Symfony's documentation, you can use AuthorizationCheckerInterface: https://symfony.com/doc/current/security.html#security-securing-controller
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
/**
* @Route("/my-link", name="my_link")
*/
public function my_link_action(AuthorizationCheckerInterface $authChecker)
{
if (true === $authChecker->isGranted('ROLE_SUPER_ADMIN')) {
// Do Super Admin's stuff
} else if (true === $authChecker->isGranted('ROLE_USER')) {
// Do user's stuff
} else {
// Do other stuff
}
...
}
Upvotes: 1