ASP.NET Forms 身份验证概述
Forms 身份验证提供了一种方法,使您可以使用自己的代码对用户进行身份验证,然后将身份验证标记保留在 Cookie 或页的 URL 中。Forms 身份验证通过 FormsAuthenticationModule 参与 ASP.NET 页的生命周期。可以通过 FormsAuthentication 类访问 Forms 身份验证信息和功能。
若要使用 Forms 身份验证,可以创建一个登录页。该登录页既收集了用户的凭据,又包括验证这些凭据时所需的代码。如果这些凭据有效,可以调用 FormsAuthentication 类的方法,以便使用适当的身份验证票证 (Cookie) 将请求重定向到最初请求的资源。如果不需要进行重定向,只需获取 Forms 身份验证 Cookie 或对其进行设置即可。
使用 authentication 配置元素对 Forms 身份验证进行配置。最简单的情况是,在 Web.config 文件或单独的文件中,可以通过指定 URL 将未经身份验证的请求重定向到某个登录页,然后提供该登录页的最小实现,并提供有效的凭据。下面的示例演示配置文件的一部分。该配置文件为 Authenticate 方法指定了登录页和身份验证凭据。密码已经使用 HashPasswordForStoringInConfigFile 方法进行加密。
<authentication mode="Forms">
<forms name="SavingsPlan" loginUrl="/Logon.aspx">
<credentials passwordFormat="SHA1">
<user name="Kim"
password="07B7F3EE06F278DB966BE960E7CBBD103DF30CA6"/>
<user name="John"
password="BA56E5E0366D003E98EA1C7F04ABF8FCB3753889"/>
</credentials>
</forms>
</authentication>
成功通过身份验证之后,FormsAuthenticationModule 模块将会使用经过身份验证的用户信息填充当前的 User 属性。下面的代码示例演示如何以编程方式读取经过 Forms 身份验证的用户的标识。
public sealed class FormsAuthenticationModule : IHttpModule
在应用程序的配置文件的 authentication 元素(ASP.NET 设置架构) 元素中将身份验证 Mode 设置为 Forms 的情况下,FormsAuthenticationModule 将当前 HttpContext.User 属性设置为表示当前请求的用户标识的 IPrincipal 对象。
FormsAuthenticationModule 公开一个 Authenticate 事件,使您可以为当前 HttpContext 的 User 属性提供一个自定义的 IPrincipal 对象。Authenticate 事件是通过在您的 ASP.NET 应用程序的 Global.asax 文件中指定一个名为 FormsAuthentication_OnAuthenticate 的子例程来访问的。
示例 下面的示例使用 FormsAuthentication_OnAuthenticate 事件将当前 HttpContext 的 User 属性设置为自定义 IPrincipal 对象。C#
public void FormsAuthentication_OnAuthenticate(object sender, FormsAuthenticationEventArgs args) { if (FormsAuthentication.CookiesSupported) { if (Request.Cookies[FormsAuthentication.FormsCookieName] != null) { try { FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt( Request.Cookies[FormsAuthentication.FormsCookieName].Value); args.User = new System.Security.Principal.GenericPrincipal( new Samples.AspNet.Security.MyFormsIdentity(ticket), new string[0]); } catch (Exception e) { // Decrypt method failed. } } } else { throw new HttpException("Cookieless Forms Authentication is not " + "supported for this application."); } }

浙公网安备 33010602011771号