ASP.NET how to access User.Identity.IsAuthenticated in Aplication Request module?

风流意气都作罢 提交于 2019-12-11 01:51:31

问题


I am using Form Authentication Method in ASP.Net and the problem is it only protect ".aspx" files. I am trying to protect ".php" files in "kcfinder" folder from unauthenticated users.

I implemeted this class in "App_Code" folder.

public class KCChecker
{
        public static void Process(HttpApplication Application)
    {
           HttpRequest Request = Application.Context.Request;
           HttpResponse Response = Application.Context.Response;
           string url = Request.Path.ToLower();
           if (url.IndexOf("/kcfinder/") == 0 && !HttpContext.Current.User.Identity.IsAuthenticated)
            {
            Response.Redirect("/");
            }
        }
}

The problem is it always say "Object reference not set to an instance of an object." on HttpContext.Current.User.Identity.IsAuthenticated. I tried to change it to Application.Context.User.Identity.IsAuthenticated but it still shows the same error.

Is there any way I can access User Object in this custom module's Process function?


回答1:


Add the following to your web.config file:

<modules runAllManagedModulesForAllRequests="true" />



回答2:


HttpApplication.PostAuthenticateRequest Event

Add an event handler for PostAuthenticateRequest to your HttpModule and call your Process(HttpApplication) method from there.

public class AuthModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.PostAuthenticateRequest += new EventHandler(context_PostAuthenticateRequest);
    }

    public void Dispose() { }

    void context_PostAuthenticateRequest(object sender, EventArgs e)
    {
        var isAuthenticated = ((HttpApplication) sender).Context.User.Identity.IsAuthenticated;
    }
}


来源:https://stackoverflow.com/questions/11218117/asp-net-how-to-access-user-identity-isauthenticated-in-aplication-request-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!