且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查用户是否在控制器内登录 Symfony2?

更新时间:2023-11-17 12:44:16

警告:如果用户使用记住我"功能.

Warning: Checking for 'IS_AUTHENTICATED_FULLY' alone will return false if the user has logged in using "Remember me" functionality.

根据 Symfony 2 文档,有 3 种可能性:

According to Symfony 2 documentation, there are 3 possibilities:

IS_AUTHENTICATED_ANONYMOUSLY - 自动分配给以下用户在网站的防火墙保护部分中,但实际上并没有已登录.这只有在允许匿名访问的情况下才有可能.

IS_AUTHENTICATED_ANONYMOUSLY - automatically assigned to a user who is in a firewall protected part of the site but who has not actually logged in. This is only possible if anonymous access has been allowed.

IS_AUTHENTICATED_REMEMBERED - 自动分配给一个用户通过记住我的 cookie 进行身份验证.

IS_AUTHENTICATED_REMEMBERED - automatically assigned to a user who was authenticated via a remember me cookie.

IS_AUTHENTICATED_FULLY - 自动分配给具有在当前会话期间提供了他们的登录详细信息.

IS_AUTHENTICATED_FULLY - automatically assigned to a user that has provided their login details during the current session.

这些角色代表三个级别的身份验证:

Those roles represent three levels of authentication:

如果您拥有 IS_AUTHENTICATED_REMEMBERED 角色,那么您还拥有IS_AUTHENTICATED_ANONYMOUSLY 角色.如果你有IS_AUTHENTICATED_FULLY 角色,那么你还有另外两个角色.换句话说,这些角色代表了三个层次的增加身份验证的强度".

If you have the IS_AUTHENTICATED_REMEMBERED role, then you also have the IS_AUTHENTICATED_ANONYMOUSLY role. If you have the IS_AUTHENTICATED_FULLY role, then you also have the other two roles. In other words, these roles represent three levels of increasing "strength" of authentication.

我遇到了一个问题,我们系统中使用过记住我"功能的用户在只检查了 'IS_AUTHENTICATED_FULLY' 的页面上被视为根本没有登录过.

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:

$securityContext = $this->container->get('security.authorization_checker');
if ($securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
    // authenticated REMEMBERED, FULLY will imply REMEMBERED (NON anonymous)
}

希望这能让其他人免于犯我犯过的同样错误.在查找如何检查某人是否在 Symfony 2 上登录时,我使用这篇文章作为参考.

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.

来源:http://symfony.com/doc/2.3/cookbook/security/remember_me.html#forcing-the-user-to-re-authenticate-before-accessing-certain-resources