aspxtreme

Login.aspx File

Designing Secure ASP.NET Applications   Forms Authentication Using an XML Users File


Login.aspx is the file to which the request gets redirected if ASP.NET does not find the form with the request. The URL of the file should be set up in the aplication root configuration file. A form containing two text boxes ( 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 checks to see if this name and password is contained in an XML file located in this directory. If it is, the user is redirected to Default.aspx. If it is not, the Adduser.aspx file is called.

To implement this functionality

  1. Import the necessary namespaces.
    <%@ Page LANGUAGE = "c#" %>
    <%@ Import Namespace = "System.Data" %>
    <%@ Import Namespace = "System.Data.SqlClient" %>
    <%@ Import Namespace = "System.Web.Security " %>
    <%@ Import Namespace = "System.IO" %>
    
    <html>
    <head>
    <title>Forms Authentication</title>
  2. Create a script section for the code.
    <script runat=server>
  3. Implement a Login_Click function.
    private void Login_Click ( Object sender, EventArgs E )
    {
    1. If the page is not valid, tell the user.
      if ( !Page.IsValid ) {
          Msg.Text = "Some required fields are missing";
          return;
      }
    2. Set up a string named cmd that is initialized to UserEmail = "MyName", where MyName is the user's e-mail name.
      String cmd = "UserEmail='" + UserEmail.Value + "'";
    3. Instantiate a new DataSet object.
      DataSet ds = new DataSet ( );
    4. Read in the XML file containing authenticated user name and password combinations. The retrieved data resides in ds, the DataSet instantiated in the previous step.

      NOTE: For the sake of simplicity and the learning experience, the following code does not follow best design practice. It does not invoke any file-locking or file-sharing flags. Also, in a real Web site, it would probably be desirable to use a relational database for the list of authenticated users.

      FileStream fs = new FileStream ( Server.MapPath ( "users.xml" ), 
                                          FileMode.Open,FileAccess.Read );
      StreamReader reader = new StreamReader ( fs );
      ds.ReadXml ( reader );
      fs.Close ( );
    5. Instantiate a new DataTable named users that is initialized to ds.
      DataTable users = ds.Tables [ 0 ];
    6. Check for any matches between the Logon name and the list of names in Users.aspx. For each match found, record the name in a DataRow named matches.

      NOTE: For the sake of simplicity, this example expects each name to be unique; therefore only the first match found is used.

      DataRow [  ] matches = users.Select ( cmd );
    7. Check each of the name matches found in the previous step to see if there is a matching password for any of them.
      if ( matches != null && matches.Length > 0 )
      {
    8. If at least one name match is found, check for password matches.
          DataRow row = matches [ 0 ];
          String pass = ( String ) row [ "UserPassword" ];
          if ( 0 != String.Compare ( pass, UserPass.Value, false ) )
          //**********************************************
          // If no password match is found, tell the user.
          //**********************************************
              Msg.Text = "Invalid Password: Please try again";
          else 
          //*************************************************
          // If a password match is found, redirect the request
          // to the originally requested resource ( Default.aspx ).
          //*************************************************
              FormsAuthentication.RedirectFromLoginPage ( UserEmail.Value, 
                                                  PersistForms.Checked );
      }
      else {
    9. If no name matches were found, redirect the request to the Add Users page. First, construct a URL string, and then use the string in a Response.Redirect command.
              StringBuilder url = new StringBuilder ( );
              url.Append ( "adduser/adduser.aspx?" );
              url.Append ( Request.ServerVariables [ "QUERY_STRING" ] );
              url.Append ( "&UserEmail = " );
              url.Append ( Server.UrlEncode ( UserEmail.Value ) );
              url.Append ( "&UserPassword = " );
              url.Append ( Server.UrlEncode ( UserPass.Value ) );
              Response.Redirect ( url.ToString ( ) );
          }
      }
      </script>
      <body>
  4. Display a form to collect the logon information.
    <form runat=server>
        <h3>Login Page</h3>
    
        <table>
            <tr>
    1. Create a User E-mail Name text box.
              <td>Email:</td>
              <td><input id = "UserEmail" type = "text" runat=server/></td>
              <td><ASP:RequiredFieldValidator 
                  ControlToValidate = "UserEmail" 
                  Display = "Static"
                  ErrorMessage = "*"
                  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 = "*"
                  runat=server/>
              </td>
          </tr>
          <tr>
    3. Create a Persistent Forms check box. If the Persistent Forms box is checked, the form will be valid across browser sessions. Otherwise, when the browser is closed, the form is destroyed.
              <td>Persistent Forms:</td>
              <td><ASP:CheckBox id=PersistForms runat = "server"
                  autopostback = "true" />
              </td>
              <td></td>
          </tr>
      
      </table>
    4. Create a Submit button that causes the Login_Click event to be fired on postback.
      <input type = "submit" onServerClick = "Login_Click" Value = "Login" 
         runat = "server" /><p>
      <asp:Label id = "Msg" ForeColor = "red" Font-Name = "Verdana" 
         Font-Size = "10" runat=server />
      
      </form>
      </body>
      </html>
See Also

The Forms Authentication Provider



Books and more ...


Suggested Reading

Need a break ?



Previous page Back to top Next page

Check out related books at Amazon

© 2000-2008 Rey Nuñez All rights reserved.

If you have any question, comment or suggestion
about this site, please send us a note

You can help support aspxtreme