AuthenticateRequest事件

时间:2009-05-17 20:53:36

标签: c# asp.net authentication forms-authentication httpapplication


问1.根据我的理解,FormsAuthenticationModule订阅AuthenticateRequest事件,因此只有在此事件被触发后才会调用FormsAuthenticationModule。但是下面的引言让我有些困惑:

  1.   

    AuthenticateRequest事件表示配置的身份验证机制已对当前请求进行了身份验证。

    • 以上引用是否表明当引发AuthenticateRequest事件时,请求(也就是用户)已经过身份验证?
  2.   

    订阅AuthenticateRequest事件可确保在处理附加模块或事件处理程序之前对请求进行身份验证。

    • 据我所知,如果我们订阅AuthenticatedRequest,那么我们的事件处理程序将在FormsAuthenticationModule之前调用?因此,在调用Application_AuthenticateRequest()之前会调用FormsAuthenticationModule吗?

  3. 问2.我正在学习的书建议在Application_AuthenticateRequest()内我们能够验证用户是否是特定角色的成员,如果没有,我们可以自动添加用户:

        protected void Application_AuthenticateRequest(Object sender, EventArgs e)
        {
                if (User.Identity.IsAuthenticated && Roles.Enabled)
                {
    
                    //here we can subscribe user to a role via Roles.AddUserToRole()
                }       
        }
    

    从上面的代码判断,调用Application_AuthenticateRequest()后会调用FormsAuthenticationModule,但在其他地方同一本书暗示Application_AuthenticateRequest()之前调用了FormsAuthenticationModule

      
        在执行身份验证之前调用

    Application_AuthenticateRequest。     这是创建自己的身份验证逻辑的起点。

      


    我错过了什么?


    感谢名单

2 个答案:

答案 0 :(得分:51)

似乎首先处理FormsAuthenticationModule。此模块通常早于ASP.NET管道中的任何自定义模块,因此当激活AuthenticateRequest时,将首先调用FormsAuthenticationModule,执行其工作,然后调用模块的事件处理程序。

如果您真的想深入研究这个问题,我建议您尝试自己调试ASP.NET代码。以下是如何设置VS的帖子:

http://weblogs.asp.net/scottgu/archive/2008/01/16/net-framework-library-source-code-now-available.aspx

编辑:我可以通过在Global.asax中设置包含自定义模块和事件处理程序的Web项目来确认此行为。看一下HttpApplication.InitInternal的源代码,初始化顺序如下:

  • 集成模块的初始化:FormsAuthenticationModule连接到HttpApplication.AuthenticateRequest事件
  • 自定义模块的初始化:自定义模块连接到HttpApplication.AuthenticateRequest事件
  • 初始化Global类(global.asax):这里我们连接到AuthenticateRequest事件
  • HttpApplication.InitInternal在特定名称模式(例如Application_AuthenticateRequest)之后搜索Global类上的方法,将它们与事件匹配并挂钩

初始化后,当AuthenticateRequest触发时,事件处理程序按初始化的顺序调用,所以:

  • FormsAuthenticationModule.AuthenticateRequest事件处理程序
  • CustomModule.AuthenticateRequest事件处理程序
  • Global.AuthenticateRequest事件处理程序
  • Global.Application_AuthenticateRequest方法

除非我遗漏了某些内容,否则没有停止触发事件处理程序的机制,因此无论FormsAuthenticationModule.AuthenticateRequest的结果如何,仍将调用下一个处理程序。我希望有所帮助。

答案 1 :(得分:5)

如果您想要访问User对象,我建议您使用

protected void Application_Start()
{
    PostAuthenticateRequest += Application_PostAuthenticateRequest;
}

protected void Application_PostAuthenticateRequest(object sender, EventArgs e)
{
    if(User.Identity.IsAuthenticated)
    {
        //Do stuff here
    }
}
相关问题