表單驗證FormsAuthentication

本主題中的範例示範 ASP.NET 表單驗證的簡單實作,目的是要說明如何使用表單驗證,讓使用者登入 ASP.NET 應用程式的基礎。

Note注意事項

有個使用表單驗證的便利方式,就是使用 ASP.NET 成員資格和 ASP.NET 登入控制項。ASP.NET 成員資格提供儲存和管理使用者資訊的方式,並且包含驗證使用者的方法。ASP.NET 登入控制項可以配合 ASP.NET 成員資格,並且封裝必要的邏輯以提示使用者輸入認證、驗證使用者、復原或取代密碼等。實際上,ASP.NET 成員資格和 ASP.NET 登入控制項會提供表單驗證的抽象層,並且取代使用表單驗證時通常會進行的大部分或所有工作。如需詳細資訊,請參閱使用成員資格管理使用者ASP.NET 登入控制項概觀

在範例的情況中,使用者要求受保護的資源 (也就是名為 Default.aspx 的網頁)。只有一個使用者能夠存取受保護的資源:jchen@contoso.com,密碼是 "37Yj*99P"。使用者名稱和密碼是使用硬式編碼方式寫入 Login.aspx 檔案中。本範例需要三個檔案:Web.config 檔、名為 Logon.aspx 及 Default.aspx 的網頁,這些檔案都在應用程式根目錄中。

若要設定表單驗證的應用程式

  1. 如果應用程式在根目錄中有 Web.config 檔,請開啟它。

  2. 如果應用程式在應用程式根資料夾中沒有 Web.config 檔,請建立名為 Web.config 的文字檔,然後加入下列項目:

      CopyCode image複製程式碼
    <?xml version="1.0"?>
                    <configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
                    <system.web>
                    </system.web>
                    </configuration>
  3. 在 system.web 項目中建立 authentication 項目,然後將其 mode 屬性設定為 Forms,如下列程式碼範例所示:

      CopyCode image複製程式碼
    <system.web>
                    <authentication mode="Forms">
                    </authentication>
                    </system.web>
  4. 在 authentication 項目中建立 forms 項目,然後設定下列屬性:

    • loginUrl:設定為 "Logon.aspx"。Logon.aspx 是當 ASP.NET 找不到要求的驗證 Cookie 時,用於重新導向的 URL。

    • name:設定為 ".ASPXFORMSAUTH"。這會設定包含驗證票證的 Cookie 名稱後置字元。

      CopyCode image複製程式碼
    <system.web>
                    <authentication mode="Forms">
                    <forms loginUrl="Logon.aspx" name=".ASPXFORMSAUTH">
                    </forms>
                    </authentication>
                    </system.web>
  5. 在 system.web 項目中建立 authorization 項目。

      CopyCode image複製程式碼
    <system.web>
                    <authentication mode="Forms">
                    <forms loginUrl="Logon.aspx" name=".ASPXFORMSAUTH">
                    </forms>
                    </authentication>
                    <authorization>
                    </authorization>
                    </system.web>
  6. 在 authorization 項目中建立 deny 項目,然後將其 users 屬性設定為 "?"。這會指定未經驗證的使用者 (以 "?" 表示) 會被拒絕存取應用程式中的資源。

      CopyCode image複製程式碼
    <system.web>
                    <authentication mode="Forms">
                    <forms loginUrl="logon.aspx" name=".ASPXFORMSAUTH">
                    </forms>
                    </authentication>
                    <authorization>
                    <deny users="?" />
                    </authorization>
                    </system.web>
  7. 儲存並關閉 Web.config 檔案。

建立登入頁面

如果使用者在先前尚未經過驗證而要求網站的任何網頁時,他們就會被重新導向至名為 Logon.aspx 的網頁。稍早您在 Web.config 檔中已指定了這個檔案名稱。

Logon.aspx 網頁會收集使用者認證 (電子郵件位址和密碼) 並加以驗證。如果使用者成功通過驗證,登入頁面就會將使用者重新導向至原始要求的網頁。在這個範例中,有效的認證會硬式編碼在網頁程式碼中。

若要建立登入頁面

  1. 在應用程式根資料夾中建立名為 Logon.aspx 的 ASP.NET 網頁。

  2. 將下列標記和程式碼複製到這個網頁中:

    Visual Basic  CopyCode image複製程式碼
    <%@ Page Language="VB" %>
                    <%@ Import Namespace="System.Web.Security" %>
                    <script runat="server">
                    Sub Logon_Click(ByVal sender As Object, ByVal e As EventArgs)
                    If ((UserEmail.Text = "jchen@contoso.com") And _
                    (UserPass.Text = "37Yj*99Ps")) Then
                    FormsAuthentication.RedirectFromLoginPage _
                    (UserEmail.Text, Persist.Checked)
                    Else
                    Msg.Text = "Invalid credentials. Please try again."
                    End If
                    End Sub
                    </script>
                    <html>
                    <head id="Head1" runat="server">
                    <title>Forms Authentication - Login</title>
                    </head>
                    <body>
                    <form id="form1" runat="server">
                    <h3>
                    Logon Page</h3>
                    <table>
                    <tr>
                    <td>
                    E-mail address:</td>
                    <td>
                    <asp:TextBox ID="UserEmail" runat="server" /></td>
                    <td>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1"
                    ControlToValidate="UserEmail"
                    Display="Dynamic"
                    ErrorMessage="Cannot be empty."
                    runat="server" />
                    </td>
                    </tr>
                    <tr>
                    <td>
                    Password:</td>
                    <td>
                    <asp:TextBox ID="UserPass" TextMode="Password"
                    runat="server" />
                    </td>
                    <td>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator2"
                    ControlToValidate="UserPass"
                    ErrorMessage="Cannot be empty."
                    runat="server" />
                    </td>
                    </tr>
                    <tr>
                    <td>
                    Remember me?</td>
                    <td>
                    <asp:CheckBox ID="Persist" runat="server" /></td>
                    </tr>
                    </table>
                    <asp:Button ID="Submit1" OnClick="Logon_Click" Text="Log On"
                    runat="server" />
                    <p>
                    <asp:Label ID="Msg" ForeColor="red" runat="server" />
                    </p>
                    </form>
                    </body>
                    </html>

    C#  CopyCode image複製程式碼
    <%@ Page Language="C#" %>
                    <%@ Import Namespace="System.Web.Security" %>
                    <script runat="server">
                    void Logon_Click(object sender, EventArgs e)
                    {
                    if ((UserEmail.Text == "jchen@contoso.com") &&
                    (UserPass.Text == "37Yj*99Ps"))
                    {
                    FormsAuthentication.RedirectFromLoginPage
                    (UserEmail.Text, Persist.Checked);
                    }
                    else
                    {
                    Msg.Text = "Invalid credentials. Please try again.";
                    }
                    }
                    </script>
                    <html>
                    <head id="Head1" runat="server">
                    <title>Forms Authentication - Login</title>
                    </head>
                    <body>
                    <form id="form1" runat="server">
                    <h3>
                    Logon Page</h3>
                    <table>
                    <tr>
                    <td>
                    E-mail address:</td>
                    <td>
                    <asp:TextBox ID="UserEmail" runat="server" /></td>
                    <td>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1"
                    ControlToValidate="UserEmail"
                    Display="Dynamic"
                    ErrorMessage="Cannot be empty."
                    runat="server" />
                    </td>
                    </tr>
                    <tr>
                    <td>
                    Password:</td>
                    <td>
                    <asp:TextBox ID="UserPass" TextMode="Password"
                    runat="server" />
                    </td>
                    <td>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator2"
                    ControlToValidate="UserPass"
                    ErrorMessage="Cannot be empty."
                    runat="server" />
                    </td>
                    </tr>
                    <tr>
                    <td>
                    Remember me?</td>
                    <td>
                    <asp:CheckBox ID="Persist" runat="server" /></td>
                    </tr>
                    </table>
                    <asp:Button ID="Submit1" OnClick="Logon_Click" Text="Log On"
                    runat="server" />
                    <p>
                    <asp:Label ID="Msg" ForeColor="red" runat="server" />
                    </p>
                    </form>
                    </body>
                    </html>

    網頁會包含收集使用者資訊的 ASP.NET 伺服器控制項,以及能夠讓使用者按下以保存登入認證的核取方塊。[登入] 按鈕的 Click 處理常式,包含以硬式編碼值檢查使用者電子郵件位址和密碼的程式碼 (密碼是包含各種非英數字元的強式密碼,並且長度最少要八個字元)。如果使用者的認證是正確的,程式碼便會呼叫 FormsAuthentication 類別的 RedirectFromLoginPage 方法,並傳遞使用者的名稱,以及表示是否要將驗證票證保留為 Cookie 的布林值 (衍生自核取方塊)。此方法會將使用者重新導向至原始要求的網頁。如果使用者的認證不符合,就會顯示錯誤訊息。請注意,網頁會匯入包含 FormsAuthentication 類別的 System.Web.Security 命名空間。

建立預設網頁

您將針對這個範例,在應用程式的根資料夾中建立 ASP.NET 網頁。因為您在組態檔中指定所有未經驗證的使用者都無法存取應用程式的 ASP.NET 資源 (其中包含 .aspx 檔案,但是不包含如 HTML 檔案或是影像、音樂等多媒體檔案之類的靜態檔案),所以當使用者要求網頁時,表單驗證會檢查使用者的認證,並在必要時將使用者重新導向至登入頁面。您建立的網頁也會允許使用者登出,以清除保留的驗證票證 (Cookie)。

若要建立預設網頁

  1. 在應用程式根資料夾中建立名為 Default.aspx 的 ASP.NET 網頁。

  2. 將下列標記和程式碼複製到這個網頁中:

    Visual Basic  CopyCode image複製程式碼
    <%@ Page Language="VB" %>
                    <html>
                    <head>
                    <title>Forms Authentication - Default Page</title>
                    </head>
                    <script runat="server">
                    Sub Page_Load(ByVal Src As Object, ByVal e As EventArgs)
                    Welcome.Text = "Hello, " & Context.User.Identity.Name
                    End Sub
                    Sub Signout_Click(ByVal sender As Object, ByVal e As EventArgs)
                    FormsAuthentication.SignOut()
                    Response.Redirect("Logon.aspx")
                    End Sub
                    </script>
                    <body>
                    <h3>
                    Using Forms Authentication</h3>
                    <asp:Label ID="Welcome" runat="server" />
                    <form id="Form1" runat="server">
                    <asp:Button ID="Submit1" OnClick="Signout_Click"
                    Text="Sign Out" runat="server" /><p>
                    </form>
                    </body>
                    </html>

    C#  CopyCode image複製程式碼
    <%@ Page Language="C#" %>
                    <html>
                    <head>
                    <title>Forms Authentication - Default Page</title>
                    </head>
                    <script runat="server">
                    void Page_Load(object sender, EventArgs e)
                    {
                    Welcome.Text = "Hello, " + Context.User.Identity.Name;
                    }
                    void Signout_Click(object sender, EventArgs e)
                    {
                    FormsAuthentication.SignOut();
                    Response.Redirect("Logon.aspx");
                    }
                    </script>
                    <body>
                    <h3>
                    Using Forms Authentication</h3>
                    <asp:Label ID="Welcome" runat="server" />
                    <form id="Form1" runat="server">
                    <asp:Button ID="Submit1" OnClick="Signout_Click"
                    Text="Sign Out" runat="server" /><p>
                    </form>
                    </body>
                    </html>

    網頁會顯示使用者經過驗證的識別,這個識別是經由 FormsAuthentication 類別所設定,並且在 ASP.NET 網頁中當做 Context.User.Identity.Name 屬性使用。[登出] 按鈕的 Click 處理常式包含了呼叫 SignOut 方法的程式碼,以清除使用者識別並移除驗證票證 (Cookie)。然後會將使用者重新導向至登入頁面。

請參閱

申明

非源创博文中的内容均收集自网上,若有侵权之处,请及时联络,我会在第一时间内删除.再次说声抱歉!!!

博文欢迎转载,但请给出原文连接。

原文地址:https://www.cnblogs.com/Athrun/p/611594.html