此示例展示 ASP.NET Forms 身份验证可能的最简单的实现。它旨在于阐释有关如何创建使用 Forms 身份验证的 ASP.NET 应用程序的基础知识。有关使用 XML 文件来保存用户名和密码的 Forms 身份验证的更复杂示例,请参见使用 XML 用户文件的 Forms 身份验证。
在此方案中,客户请求受保护的资源 Default.aspx。只有下面这一个用户可以获得对该受保护资源的访问权限:jdoe@somewhere.com,密码为 password。该用户名和密码已硬编码到 Logon.aspx 文件中。这里涉及三个文件:Web.config、Logon.aspx 和 Default.aspx。这些文件驻留在应用程序根目录下。这些文件的代码将在下面的讨论中进行分析。
Web.config
应设置 Web.config 配置文件以具有下列项,并将该配置文件放在应用程序根目录(Default.aspx 驻留的目录)中。
<configuration>
<system.web>
安装 Web.config 配置文件
将身份验证模式设置为 Forms。其他可能的值为 Windows、Passport 和 None(空字符串)。此示例中,必须为 Forms。
<authentication mode="Forms">
设置 Forms 身份验证属性。
<forms
将 loginUrl 属性设置为“logon.aspx”。如果 ASP.NET 没有找到针对请求的身份验证 Cookie,则 Logon.aspx 是用于重定向的 URL。
loginUrl = "logon.aspx"
设置该 Cookie 的名称后缀。
name = ".ASPXFORMSAUTH"/>
拒绝未经身份验证的用户访问此目录。
</authentication>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
</configuration>
Logon.aspx
Logon.aspx 是当 ASP.NET 没有找到针对请求的身份验证票时,该请求被重定向到的文件。此文件名是在 Web.config(即配置文件)中指定的。向客户端用户提供了一个窗体,该窗体包含两个文本框(“用户电子邮件名称”和“密码”)和一个“提交”按钮。用户输入电子邮件名称和密码,然后单击“提交”按钮。然后代码将此名称和密码与硬编码在 If 语句中的相应对进行比较。如果比较成功,则将用户连接到 Default.aspx;如果失败,则向用户显示错误信息。
实现登录功能
导入必需的命名空间。
<%@ Import Namespace="System.Web.Security" %>
设置脚本语言。
<html>
[Visual Basic]
<script language="VB" runat=server>
[C#]
<script language="C#" runat=server>
创建 Logon_Click 事件处理程序来处理提交事件。
[Visual Basic]
Sub Logon_Click(sender As Object, e As EventArgs)
[C#]
void Logon_Click(Object sender, EventArgs e)
{
通过对输入名称和密码与硬编码到代码中的名称和密码(jchen@contoso.com 和 password)进行比较来验证用户的身份。如果比较成功,则将请求重定向到受保护的资源 (Default.aspx)。如果比较失败,则显示错误信息。
[Visual Basic]
If ((UserEmail.Value = "jchen@contoso.com") And _
(UserPass.Value = "password")) Then
FormsAuthentication.RedirectFromLoginPage _
(UserEmail.Value, Persist.Checked)
Else
Msg.Text = "Invalid Credentials: Please try again."
End If
End Sub
</script>
[C#]
if ((UserEmail.Value == "jchen@contoso.com") &&
(UserPass.Value == "password"))
{
FormsAuthentication.RedirectFromLoginPage
(UserEmail.Value, Persist.Checked);
}
else
{
Msg.Text = "Invalid Credentials: Please try again.";
}
}
</script>
显示窗体以收集登录信息。
<body>
<form runat=server>
<h3><font face="Verdana">Logon Page</font></h3>
<table>
<tr>
创建“用户电子邮件名称”(User E-mail Name) 文本框。添加一个必填字段验证程序控件和一个检查电子邮件输入是否有效的正则表达式验证程序控件。
<td>Email:</td>
<td><input %>
<html>
<head>
<title>Forms Authentication</title>
<script runat=server>
Sub Page_Load(Src As Object, e As EventArgs)
Welcome.InnerHtml = "Hello, " + Context.User.Identity.Name
End Sub
Sub Signout_Click(sender As Object, e As EventArgs)
FormsAuthentication.SignOut()
Response.Redirect("logon.aspx")
End Sub
</script>
<body>
<h3><font face="Verdana">Using Forms Authentication</font></h3>
<span );
}
</script>
<body>
<h3><font face="Verdana">Using Forms Authentication</font></h3>
<span /><p>
</form>
</body>
</html>