Request.IsAuthenticated永远不会是真的

时间:2014-05-29 22:31:28

标签: 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 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("/");
        }
    }
}

我不知道为什么会发生这种情况,但在访问true目录时,条件总是评估为/courses/

修改

我在Web.Config中找到了这个。不确定它是否相关。

<authentication mode="Forms">
  <forms loginUrl="userlogin.asp" name=".cc" protection="All" path="/" timeout="2880" slidingExpiration="true" />
</authentication>

我做错了吗?我该如何解决这个问题?

1 个答案:

答案 0 :(得分:4)

作为第一个事件的BeginRequest太早,无法询问用户是否经过身份验证。

此时,您可以通过直接读取cookie来简单检查其是否经过身份验证:

string cookieName = FormsAuthentication.FormsCookieName;    
HttpCookie authCookie = Context.Request.Cookies[cookieName];

if (null == authCookie || FormsAuthentication.Decrypt(authCookie.Value) == null)
{
    // is not authenticated
}