Asp.net Request.IsAuthenticated永远不为true
我已经实现了一个Asp.net Request.IsAuthenticated永远不为true,asp.net,authentication,httprequest,httpmodule,httpcontext,Asp.net,Authentication,Httprequest,Httpmodule,Httpcontext,我已经实现了一个HttpModule,它应该限制对我网站/courses/目录的访问,但它有一个主要问题 Request.IsAuthenticated始终为false 代码如下: using System; using System.Web; public class CourseAuthenticationModule : IHttpModule { public void Dispose() { } public void Init(HttpApplication co
HttpModule
,它应该限制对我网站/courses/
目录的访问,但它有一个主要问题
Request.IsAuthenticated
始终为false
代码如下:
using System;
using System.Web;
public class CourseAuthenticationModule : IHttpModule
{
public void Dispose() { }
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(BeginRequest);
}
public void BeginRequest(Object source, EventArgs e)
{
HttpApplication app = (HttpApplication)source;
HttpContext context = app.Context;
HttpRequest request = context.Request;
HttpResponse response = context.Response;
if (request.Path.ToLower().StartsWith("/courses/")
&& !request.IsAuthenticated)
{
response.Redirect("/");
}
}
}
我不知道为什么会发生这种情况,但在访问/courses/
目录时,该条件将始终计算为true
编辑:
我在Web.Config中找到了这个。不确定是否相关
<authentication mode="Forms">
<forms loginUrl="userlogin.asp" name=".cc" protection="All" path="/" timeout="2880" slidingExpiration="true" />
</authentication>
我做错什么了吗?如何解决此问题?作为第一个事件的BeginRequest太早,无法询问用户是否经过身份验证 此时,您可以通过直接读取cookie来简单检查其是否经过身份验证:
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Context.Request.Cookies[cookieName];
if (null == authCookie || FormsAuthentication.Decrypt(authCookie.Value) == null)
{
// is not authenticated
}
您使用的是哪种身份验证?你能给我们看一下代码吗?看更新的问题@Kenneth@kehrk尝试附加
IIdentity
以查看FormsAuthentication.Decrypt()是否可以使用字符串,而不是HttpCookie
:与'System.Web.Security.FormsAuthentication.Decrypt(string)'匹配的最佳重载方法具有一些无效参数,使用cookie的字符串,我从内存中键入它,犯了这个错误。我已经更新了答案,但也检查了身份,将其添加到您的课堂,这可能是直接的工作。不用担心。我想这差不多行得通,但我明天还要去拿。非常感谢你的帮助!亚里士多德关于开始请求太早的说法是对的。您需要在Application_AuthenticateRequest事件中检查它。然而,这还不够。为了使request.IsAuthenticated的计算结果为true,您需要通过代码或内置成员资格服务将request.Identity对象设置为支持IsAuthenticated iface成员的对象。