此示例展示 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 id="UserEmail" type="text" runat=server/></td>
        <td><ASP:RequiredFieldValidator
                 ControlToValidate="UserEmail"
                 Display="Static"
                 ErrorMessage="Cannot be empty."
                 runat=server/>
        </td>
        <td><asp:RegularExpressionValidator id="RegexValidator"
                 ControlToValidate="UserEmail"
                 ValidationExpression="^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"
                 EnableClientScript="false"
                 Display="Static"
                 ErrorMessage="Invalid format for e-mail address."
                 runat="server"/>
        </td>
    </tr>
    <tr>
创建“密码”(Password) 文本框。
        <td>Password:</td>
        <td><input id="UserPass" type=password runat=server/></td>
        <td><ASP:RequiredFieldValidator
                 ControlToValidate="UserPass"
                 Display="Static"
                 ErrorMessage="Cannot be empty."
                 runat=server/>
        </td>
    </tr>
    <tr>
创建一个“持久性 Cookie”(Persistent Cookie) 复选框。如果选中“持久性 Cookie”框,则该 Cookie 的有效期将跨浏览器会话。否则,在关闭浏览器时将销毁该 Cookie。
        <td>Persistent Cookie:</td>
        <td><ASP:CheckBox id=Persist runat="server"
                 autopostback="true"/>
        </td>
        <td></td>
    </tr>
</table>
创建在回发时激发 Logon_Click 事件的“提交”按钮。
<input type="submit" OnServerClick="Logon_Click" Value="Logon"
        runat="server"/>
<p><asp:Label id="Msg" ForeColor="red" Font-Name="Verdana"
            Font-Size="10" runat=server/></p>
</form>
</body>
</html>
Default.aspx
Default.aspx 文件是被请求的、受保护的资源。它是仅显示字符串 Hello、记录的电子邮件名称和“注销”(Signout) 按钮的简单文件。
[Visual Basic]
<%@ Page LANGUAGE="VB" %>
<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 id="Welcome" runat=server/>
<form runat=server>
    <input type="submit" OnServerClick="Signout_Click" Value="Signout"                                                    
           runat="server"/><p>
</form>
</body>
</html>
[C#]
<%@ Page LANGUAGE="C#" %>
<html>
<head>
<title>Forms Authentication</title>
<script runat=server>
    private void Page_Load(Object Src, EventArgs e )
    {
        Welcome.InnerHtml = "Hello, " + Context.User.Identity.Name;
    }
    private void Signout_Click(Object sender, EventArgs e)
    {
        FormsAuthentication.SignOut();
        Response.Redirect("logon.aspx");
    }
</script>

<body>
<h3><font face="Verdana">Using Forms Authentication</font></h3>
<span id="Welcome" runat=server/>
<form runat=server>
    <input type="submit" OnServerClick="Signout_Click" Value="Signout"                                                   
           runat="server"/><p>
</form>
</body>
</html>

posted on 2005-08-30 10:06  T_98Dsky   阅读(642)  评论(1编辑  收藏  举报