Request.IsAuthenticated永远不会是真的

Keh*_*mme 5 asp.net authentication httpmodule httprequest 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("/");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

编辑:

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

<authentication mode="Forms">
  <forms loginUrl="userlogin.asp" name=".cc" protection="All" path="/" timeout="2880" slidingExpiration="true" />
</authentication>
Run Code Online (Sandbox Code Playgroud)

难道我做错了什么?我怎样才能解决这个问题?

Ari*_*tos 5

BeginRequest 作为第一个事件还为时过早,无法询问用户是否已通过身份验证。

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

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

if (null == authCookie || FormsAuthentication.Decrypt(authCookie.Value) == null)
{
    // is not authenticated
}
Run Code Online (Sandbox Code Playgroud)