Compartir a través de


Simple Forms Authentication

This example presents the simplest possible implementation of ASP.NET forms authentication. It is intended to illustrate the basic fundamentals of how to create an ASP.NET application that uses forms authentication. For a more complex example of forms authentication that uses an XML file to hold user names and passwords, see Forms Authentication Using An XML Users File.

In this scenario, the client requests a protected resource, Default.aspx. There is only one user who can gain access to the protected resource: jchen@contoso.com, with a password of password. The user name and password are hard-coded into the Logon.aspx file. There are three files involved: Web.config, Logon.aspx, and Default.aspx. The files reside in the application root directory. The code in these files is analyzed in the following discussion.

Web.config

You should set up the Web.config configuration file to have the following entries and place it in the application root directory (the directory in which Default.aspx resides).

<configuration>
    <system.web>

To set up the Web.config configuration file

  1. Set the authentication mode to Forms. Other possible values are Windows, Passport, and None (empty string). For this example, it must be Forms.

            <authentication mode="Forms"> 
    
  2. Set the forms authentication attributes.

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

                  loginUrl = "logon.aspx"
      
    2. Set the cookie's name suffix.

                  name = ".ASPXFORMSAUTH"/>
      
  3. Deny unauthenticated users access to this directory.

            </authentication>
            <authorization>
                <deny users="?"/> 
            </authorization>
        </system.web>
    </configuration>
    

Logon.aspx

Logon.aspx is the file to which the request gets redirected if ASP.NET does not find the authentication ticket with the request. This file name was specified in Web.config, the configuration file. A form containing two text boxes (User E-mail Name and Password) and a Submit button is presented to the client user. The user enters the e-mail name and password, and clicks the Submit button. The code then compares this name and password to the pair that is hard-coded into the if statement. If the comparison succeeds, the user is connected to Default.aspx. If it fails, an error message is presented to the user.

To implement the logon functionality

  1. Import the necessary namespace.

    <%@ Import Namespace="System.Web.Security" %>
    
  2. Set up the script language.

        <script language="VB" runat=server>
    [C#]
        <script language="C#" runat=server>
    
  3. Create a Logon_Click event handler to handle the submit event.

            Sub Logon_Click(sender As Object, e As EventArgs)
    [C#]
            void Logon_Click(Object sender, EventArgs e) 
            {
    
  4. Authenticate the user by comparing the input name and password to those hard-coded into the code: jchen@contoso.com and password. If the comparison succeeds, redirect the request to the protected resource (Default.aspx). If the comparison fails, display an error message.

                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>
    
  5. Display a form to collect the logon information.

    <body>
    <form runat=server>
        <h3><font face="Verdana">Logon Page</font></h3>
        <table>
            <tr>
    
    1. Create a User E-mail Name text box. Add a required field validator control and a regular expression validator control that checks for a valid e-mail entry.

              <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>    
      
    2. Create a Password text box.

              <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>
      
    3. Create a Persistent Cookie check box. If the Persistent Cookie box is selected, the cookie will be valid across browser sessions. Otherwise, the cookie is destroyed when the browser is closed.

              <td>Persistent Cookie:</td>
              <td><ASP:CheckBox id=Persist runat="server"
                       autopostback="true"/>
              </td>
              <td></td>
          </tr>
      </table>
      
      
    4. Create a Submit button that causes the Logon_Click event to be raised when posted back.

      <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

The Default.aspx file is the requested, protected resource. It is a simple file that merely displays the string Hello plus the recorded e-mail name and a Signout button.

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

See Also

ASP.NET Web Application Security | Designing Secure ASP.NET Applications | Forms Authentication Using An XML Users File