如何在不拒绝访问 Symfony 4 中的控制器的情况下检查用户是否已通过身份验证
How to check if user is authenticated without denying access to controller in Symfony 4
我想检查用户是否在 Symfony 4 的控制器中通过了身份验证。基于检查,我想从数据库下载不同的数据以显示给匿名用户和经过身份验证的用户。
我的第一反应是获取用户对象并检查它是否为 null,但根据手册:https://symfony.com/doc/current/security.html#denying-access-roles-and-other-authorization 这是一个禁忌:
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()) {
// ... }
我不能使用 $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');因为我也不想拒绝匿名用户的访问,所以我只想为他们加载一组不同的数据。
那么如何在不拒绝访问的情况下检查用户是否通过身份验证?
如 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
}
...
}
我想检查用户是否在 Symfony 4 的控制器中通过了身份验证。基于检查,我想从数据库下载不同的数据以显示给匿名用户和经过身份验证的用户。
我的第一反应是获取用户对象并检查它是否为 null,但根据手册:https://symfony.com/doc/current/security.html#denying-access-roles-and-other-authorization 这是一个禁忌:
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()) { // ... }
我不能使用 $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');因为我也不想拒绝匿名用户的访问,所以我只想为他们加载一组不同的数据。
那么如何在不拒绝访问的情况下检查用户是否通过身份验证?
如 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
}
...
}