AuthenticateRequest事件

Sou*_*ceC 41 c# asp.net authentication forms-authentication httpapplication


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

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

    • 以上引用是否表明在AuthenticateRequest引发事件时,请求(也称为用户)已经过身份验证?
  2. 订阅AuthenticateRequest事件可确保在处理附加模块或事件处理程序之前对请求进行身份验证.

    • 据我所知,如果我们订阅AuthenticatedRequest,那么我们的事件处理程序将在之前被调用FormsAuthenticationModule?这样Application_AuthenticateRequest()叫之前会FormsAuthenticationModule被称为?


问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()
            }       
    }
Run Code Online (Sandbox Code Playgroud)

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

Application_AuthenticateRequest 在执行身份验证之前调用.这是创建自己的身份验证逻辑的起点.


我错过了什么?


感谢名单

bbm*_*mud 52

似乎首先处理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的结果如何,仍将调用下一个处理程序.我希望有所帮助.

  • 需要注意的是:“FormsAuthenticationModule.Authenticate”事件(不称为 *AuthenticateRequest*)在“Application.AuthenticateRequest”事件期间被调用(FormsAuthenticationModule)。您可以使用 global.asax 中的预定义名称注册该事件,就像注册任何其他事件一样。 (2认同)

She*_*kel 5

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

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

protected void Application_PostAuthenticateRequest(object sender, EventArgs e)
{
    if(User.Identity.IsAuthenticated)
    {
        //Do stuff here
    }
}
Run Code Online (Sandbox Code Playgroud)