我想检查用户是否在Symfony 4的一个控制器内通过了身份验证。基于该检查,我想从数据库下载不同的数据以显示给匿名用户和经过身份验证的用户。
我的第一个反应是获取用户对象并检查它是否为空,但是根据手册:https://symfony.com/doc/current/security.html#denying-access-roles-and-other-authorization,这是不可以的:
重点在于:始终检查用户是否已登录 使用User对象,并使用isGranted()方法(或 access_control)来做到这一点:
//是的!使用它来查看用户是否已登录 $ this-> denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
// boo :(。请勿检查User对象是否已登录 如果($ this-> getUser()){ // ...}
我不能使用$ this-> denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');由于我也不想拒绝对匿名用户的访问,因此我只想为他们加载另一组数据。
那么如何在不拒绝访问的情况下检查用户是否已通过身份验证?
答案 0 :(得分:1)
如Symfony文档中所述,您可以使用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
}
...
}