关于FormsAuthentication类(身份验证服务)
2010-09-16 16:54:54| 分类: .Net(C#) | 标签: |字号大中小 订阅
为 Web 应用程序管理 Forms 身份验证服务。无法继承此类。
命名空间: System.Web.Security
程序集: System.Web(在 System.Web.dll 中)
备注: Forms 身份验证使不要求 Windows 身份验证的 Web 应用程序可以进行用户和密码验证。使用 Forms 身份验证时,用户信息存储在外部数据源中,例如 Membership 数据库,或存储在应用程序的配置文件中。在用户通过身份验证后,Forms 身份验证即会在 Cookie 或 URL 中维护一个身份验证票证,这样已通过身份验证的用户就无需在每次请求时都提供凭据了。
可通过将 authentication 配置元素的 mode 特性设置为 Forms 来启用 Forms 身份验证。通过使用 authorization 配置元素可要求所有对应用程序的请求均需包含有效的用户身份验证票证,从而拒绝任何未知用户的请求,如下面的示例所示。配置应用程序使用 Forms 身份验证:web.config 文件
<system.web>
<authentication mode="Forms">
<forms loginUrl="login.aspx" />
</authentication>
<authorization>
<deny users="?" />
</authorization>
</system.web>
在上面的示例中,对作为应用程序的一部分的 ASP.NET 页的任何请求都需要 Forms 身份验证提供的有效用户名。如果用户名不存在,则该请求重定向到所配置的 LoginUrl。
示例:
下面的代码示例演示了一个 ASP.NET 应用程序的 Web.config 文件,该应用程序将 ASP.NET 成员资格提供程序用于 Forms 身份验证并要求对所有用户进行身份验证。
<configuration>
<connectionStrings>
<add name="SqlServices" connectionString="Data Source=MySqlServer;Integrated Security=SSPI;Initial Catalog=aspnetdb;" />
</connectionStrings>
<system.web>
<membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="20">
<providers>
<add name="SqlProvider"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="SqlServices"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
passwordFormat="Hashed"
applicationName="/" />
</providers>
</membership>
</system.web>
</configuration>
下面的代码示例演示使用 Forms 身份验证和 ASP.NET 成员资格的 ASP.NET 应用程序的登录页。
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Security" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
public void Login_OnClick(object sender, EventArgs args)
{
if (Membership.ValidateUser(UsernameTextbox.Text, PasswordTextbox.Text))
FormsAuthentication.RedirectFromLoginPage(UsernameTextbox.Text, NotPublicCheckBox.Checked);
else
Msg.Text = "Login failed. Please check your user name and password and try again.";
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Login</title>
</head>
<body>
<form id="form1" runat="server">
<h3>Login</h3>
<asp:Label id="Msg" ForeColor="maroon" runat="server" /><br />
Username: <asp:Textbox id="UsernameTextbox" runat="server" /><br />
Password: <asp:Textbox id="PasswordTextbox" runat="server" TextMode="Password" /><br />
<asp:Button id="LoginButton" Text="Login" OnClick="Login_OnClick" runat="server" />
<asp:CheckBox id="NotPublicCheckBox" runat="server" />
Check here if this is <span style="text-decoration:underline">not</span> a public computer.
</form>
</body>
</html>
关于这个类的更多知识, 可以参考:http://msdn.microsoft.com/zh-cn/library/system.web.security.formsauthentication