(HttpContext.Current.User != null) 是否足以假设 FormsAuthentication 已对用户进行身份验证
在 ASP.NET (2.0) 应用程序中,我使用 FormsAuthentication。
在 Global.asax / Application_AuthenticateRequest 方法中,我检查 HttpContext.Current.User 是否为 null。
这是否足以了解表单身份验证 cookie 是否存在、票证是否未过期以及总体而言表单身份验证机制是否已完成其验证用户的工作?
我需要这个,因为我在该应用程序中有某些页面,有时不需要身份验证即可访问(基于某些条件),并且我将它们放在 web.config 中的单独“位置”指令中,以便排除它们来自“catch all”表单身份验证。
即,我试图检查 Application_AuthenticateRequest 在此“位置”访问的页面是否需要保护,如果是,则了解用户是否已通过身份验证,或者我需要重定向到登录。
编辑:正如答案所暗示的,我很可能会选择 IsAuthenticated。 为了让我更好地理解它,这里有 2 个额外问题:)(请编辑其他答案以添加这些问题,谢谢):
我可以假设如果 IsAuthenticated 为 true,那么 HttpContext.Current.User 肯定会包含经过身份验证的用户的用户名?
如果强制执行 FormsAuthentication,并且只有少数页面被“location”指令排除,我怎样才能在 HttpContext.Current.User 中得到“匿名用户”?
In an ASP.NET (2.0) application I use FormsAuthentication.
In the Global.asax / Application_AuthenticateRequest method I check if HttpContext.Current.User is null.
Is this enough to know if the forms authentication cookie exists, the ticket is not expired, and overall, that the forms authentication mechanism has done its job to validate the user?
I need this, because I have certain pages in that application, which sometimes do not need authentication to be accessed (based on some criteria), and I put them in a separate "location" directive in web.config with in order to exclude them from "catch all" forms authentication.
I.e. I'm trying to check in Application_AuthenticateRequest if the page accessed in this "location" needs protection or not, and if yes, to know if the user have been authenticated already, or I need to redirect to Logon.
EDIT: As the answers suggest, most probably I'll go with IsAuthenticated. In order for me to grasp it better, here are 2 bonus questions :) (please, edit other answers to add these, thanks) :
Can I assume that if IsAuthenticated is true, then HttpContext.Current.User will for sure contain the username for the authenticated user?
How can I end up with an "anonymous user" in HttpContext.Current.User, if FormsAuthentication is enforced, and only few pages are excluded with "location" directive?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,
User
可能只是对匿名用户的引用。 检查HttpContext.Current.Request.IsAuthenticated
。
No, the
User
could just be a reference to the anonymous user. CheckHttpContext.Current.Request.IsAuthenticated
.我通常使用Request.IsAuthenticated。 我无法告诉你你的方法是否有效。 听起来应该是这样,尽管如果您支持匿名登录,它可能会产生副作用?
I usually use Request.IsAuthenticated. I couldn't tell you whether your approach should work or not. It sounds like it should, although it might have side effects if you support anonymous logins?
顺便说一句,请务必检查上下文是否为空(如果您在 httpmodule 中工作)。
As an aside, be sure to check the context is not null as well (incase your working in an httpmodule).