• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
只是向上走
采菊东篱下,悠然见南山。
博客园    首页    新随笔    联系   管理    订阅  订阅
怎样实现简单Forms验证(登录,注销)
How to: Implement Simple Forms Authentication

reference http://msdn.microsoft.com/en-us/library/xdt4thhy.aspx
--------------------------------------------------------------------------------------

In the scenario for the example, users request a protected resource, namely a page named Default.aspx. Only one user has access to the protected resource: jchen@contoso.com, with a password of "37Yj*99P". The user name and password are hard-coded into the Logon.aspx file. The example requires three files: the Web.config file, a page named Logon.aspx, and a page named Default.aspx. The files reside in the application root directory.

To configure the application for forms authentication

  1. If the application has a Web.config file in the application root, open it.

  2. If the application does not already have a Web.config file in the application root folder, create a text file named Web.config and add the following elements to it:

    Copy Code
    <?xml version="1.0"?>
    <configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
        <system.web>
    
        </system.web>
    </configuration>
    
  3. Within the system.web element, create an authentication element and set its mode attribute to Forms, as shown in the following example:

    Copy Code
    <system.web>
      <authentication mode="Forms">
      </authentication>
    </system.web>
    
  4. Within the authentication element, create a forms element and set the following attributes:

    • loginUrl   Set to "Logon.aspx." Logon.aspx is the URL to use for redirection if ASP.NET does not find an authentication cookie with the request.

    • name   Set to ".ASPXFORMSAUTH". This sets the suffix for the name of the cookie that contains the authentication ticket.

    Copy Code
    <system.web>
      <authentication mode="Forms">
        <forms loginUrl="Logon.aspx" name=".ASPXFORMSAUTH">
        </forms>
      </authentication>
    </system.web>
    
  5. Within the system.web element, create an authorization element.

    Copy Code
    <system.web>
      <authentication mode="Forms">
        <forms loginUrl="Logon.aspx" name=".ASPXFORMSAUTH">
        </forms>
      </authentication>
      <authorization>
      </authorization>
    </system.web>
    
  6. Within the authorization element, create a deny element and set its users attribute to "?". This specifies that unauthenticated users (represented by "?") are denied access to resources in this application.

    Copy Code
    <system.web>
      <authentication mode="Forms">
        <forms loginUrl="logon.aspx" name=".ASPXFORMSAUTH">
        </forms>
      </authentication>
      <authorization>
        <deny users="?" />
      </authorization>
    </system.web>
    
  7. Save the Web.config file and close it.

 Creating the Logon Page

When users request any page from the Web site and if they have not previously been authenticated, they are redirected to a page named Logon.aspx. You specified this file name earlier in the Web.config file.

The Logon.aspx page collects user credentials (e-mail address and password) and authenticates them. If the user is successfully authenticated, the logon page redirects the user to the page they originally requested. In the example, the valid credentials are hard-coded into the page code.

Security noteSecurity Note:

This example contains a text box that accepts user input, which is a potential security threat. By default, ASP.NET Web pages validate that user input does not include script or HTML elements. For more information, see Script Exploits Overview.

To create the logon page

  1. Create an ASP.NET page named Logon.aspx in the application root folder.

  2. Copy the following markup and code into it:

    Visual Basic
    Copy Code
    <%@ 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#
    Copy Code
    <%@ 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>

    The page contains ASP.NET server controls that collect user information and a check box that users can click to make their login credentials persistent. The Log On button's Click handler contains code that checks the user's e-mail address and password against hard-coded values. (The password is a strong password that contains various non-alphabetic characters and is at least eight characters long.) If the user's credentials are correct, the code calls the FormsAuthentication class's RedirectFromLoginPage method, passing the user's name and a Boolean value (derived from the check box) indicating whether to persist an authentication ticket as a cookie. The method redirects the user to the page originally requested. If the user's credentials do not match, an error message is displayed. Note that the page imports the System.Web.Security namespace, which contains the FormsAuthentication class.

 Creating the Default Page

For the example, you will create an ASP.NET page in the application root folder. Because you specified in the configuration file that all unauthenticated users are denied access to the application's ASP.NET resources (which includes .aspx files; but does not include static files such as HTML files or multi-media files including images, music, and so on), when a user requests the page, forms authentication will check the user's credentials and redirect the user to the logon page if necessary. The page you create will also allow users to log out, which clears their persisted authentication ticket (cookie).

To create a default page

  1. Create an ASP.NET page named Default.aspx in the application root folder.

  2. Copy the following markup and code into it:

    Visual Basic
    Copy Code
    <%@ 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#
    Copy Code
    <%@ 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>

    The page displays the user's authenticated identity, which was set by the FormsAuthentication class and is available in an ASP.NET page as the Context.User.Identity.Name property. The Sign Out button's Click handler contains code that calls the SignOut method to clear the user identity and remove the authentication ticket (cookie). It then redirects the user to the logon page.

posted on 2009-08-31 22:55  jes.shaw  阅读(708)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3