FormsAuthenticationModule在哪里注册?

4

现在我正在尝试详细了解asp.net mvc身份验证的工作原理。据我所知,FormsAuthenticationModule会检查cookie并填充HttpContext.User。但是我找不到在我的应用程序中注册FormsAuthenticationModule的地方?


1
它是在 Web 服务器层面上注册的。假设您使用 IIS 托管,请打开 IIS 管理器,选择顶级并单击“模块”,您将在那里找到它。 - Uriil
根据身份验证类型(Windows或Forms),IIS会调用相应的身份验证模块(WindowsAuthenticationModule或FormsAuthenticationModule)吗? - mtkachenko
2个回答

8

它继承自根 web.config。例如,如果您在 x64 机器上安装了 .NET 4,请打开 C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config 文件。在 system.web 部分中,您会找到以下模块注册:

<httpModules>
    <add name="OutputCache" type="System.Web.Caching.OutputCacheModule" />
    <add name="Session" type="System.Web.SessionState.SessionStateModule" />
    <add name="WindowsAuthentication" type="System.Web.Security.WindowsAuthenticationModule" />
    **<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" />**
    <add name="PassportAuthentication" type="System.Web.Security.PassportAuthenticationModule" />
    <add name="RoleManager" type="System.Web.Security.RoleManagerModule" />
    <add name="UrlAuthorization" type="System.Web.Security.UrlAuthorizationModule" />
    <add name="FileAuthorization" type="System.Web.Security.FileAuthorizationModule" />
    <add name="AnonymousIdentification" type="System.Web.Security.AnonymousIdentificationModule" />
    <add name="Profile" type="System.Web.Profile.ProfileModule" />
    <add name="ErrorHandlerModule" type="System.Web.Mobile.ErrorHandlerModule, System.Web.Mobile, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
    <add name="ServiceModel" type="System.ServiceModel.Activation.HttpModule, System.ServiceModel.Activation, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    <add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" />
    <add name="ScriptModule-4.0" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</httpModules>

ASP.NET会将所有在文件系统层次结构中找到的web.config文件合并,以便应用程序默认启用所有模块。


5
我找不到我的应用程序中注册了FormsAuthenticationModule的位置在哪里?
当您在web.config中设置时,它会被ASP.NET运行时自动注册。
如果您对细节感兴趣,可以查看ASP.NET的源代码,特别是HttpApplication类和InitModulesCommon私有方法,该方法调用FormsAuthentication模块的Init方法(如果您在web.config中注册了该模块)。
FormsAuthentication模块本身一旦注册,将订阅HTTP处理管道的AuthenticateRequest事件,并尝试基于请求中发送的表单身份验证cookie中存在的值构建当前HttpContext中的IPrincipal。

FormsAuthenticationModule是否使用应用程序中注册的成员资格提供程序来获取有关用户的数据? - mtkachenko
不,表单身份验证与会员提供程序完全没有关系。它们是两个完全不同的东西,可以独立使用。 - Darin Dimitrov
模块如何获取用户名? - mtkachenko
2
它从浏览器在每个请求中发送的Forms身份验证cookie中读取。当您使用FormsAuthentication.SetAuthCookie静态方法发出Forms身份验证cookie时,它将使用cookie中的机器密钥加密用户名。此cookie将在每个后续请求中发送,Forms身份验证模块将检查其是否存在,尝试解密它,如果成功,它将填充HttpContext.User属性。请阅读以下文章http://msdn.microsoft.com/en-us/library/ff647070.aspx,其中详细描述了整个流程。 - Darin Dimitrov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接