asp.net - Request.IsAuthenticated 从不为真

标签 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>

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

最佳答案

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

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

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

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

关于asp.net - Request.IsAuthenticated 从不为真,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23944102/

相关文章:

go - 在 Go HTTP 处理程序中使用未导出的结构键获取上下文值时为 nil

asp.net - Lucene.Net 是否管理访问同一索引的多个线程,一个索引而另一个正在搜索?

c# - 防止多行ASP :Textbox from trimming line feeds

java - context.xml 中有两个数据源的用户 'root' @'localhost' 的访问被拒绝

angular - 拦截传出链接Angular 4

android - 当请求已经在 getBody() 方法中时,是否可以取消请求?

php - [已死]如何使用异步回发成功发布到旧的 ASP.NET 站点

c# - 如何在 Web API 中支持空 RouteAttribute?

mysql - 是否可以在进行 SQL 查询的同时进行身份验证(不预先进行身份验证)

laravel - 我如何使用方法 try() - Laravel 7