Compartir a través de


How to: Implement Simple Forms Authentication

This example in this topic presents a simple implementation of ASP.NET forms authentication. It is intended to illustrate the fundamentals of how to use forms authentication to log users into an ASP.NET application.

NoteNote

A convenient way to work with forms authentication is to use ASP.NET membership and ASP.NET login controls. ASP.NET membership provides a way to store and manage user information and includes methods to authenticate users. ASP.NET login controls work with ASP.NET membership and encapsulate the logic required to prompt users for credentials, validate users, recover or replace passwords, and so on. In effect, ASP.NET membership and ASP.NET login controls provide a layer of abstraction over forms authentication and replace most or all of the work you would normally have to do to use forms authentication. For more information, see Managing Users by Using Membership and ASP.NET Login Controls Overview.

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:

    <?xml version="1.0"?>
    <configuration xmlns="https://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:

    <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.

    <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.

    <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.

    <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:

    <%@ 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>
    
    <%@ 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:

    <%@ 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>
    
    <%@ 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.

See Also

Reference

ASP.NET Login Controls Overview

Concepts

Basic Security Practices for Web Applications

Other Resources

ASP.NET Web Application Security
Managing Users by Using Membership