Authenticating Individual Users

Authentication on a Web site requires the ability to obtain user identification and a password. These are typically obtained through either a login page or a user control. Chapter 14, "ASP.NET Custom and User Controls," discusses user controls in greater depth, so the example in this chapter will use a login page (see Figure 13.1). All of the files in this section should be placed in the same project. The code for the login page is shown in Listing 13.1.

Listing 13.1 Login Page Code (Login.aspx)
 <%@ Page language="c#" Debug="true" Codebehind="Login.aspx.cs" AutoEventWireup="false" Inherits="Login.Login" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html>   <head>     <title></title>     <meta name="GENERATOR" content= "Borland ASP.NET Designer for c# Package Library 7.1">   </head>   <body ms_positioning="FlowLayout">     <form runat="server">       <p>         <asp:label  runat="server" font-bold="True">            Please Enter User Name and Password:</asp:label>       </p>         <asp:label  runat="server">User Name:</asp:label>         <asp:textbox  runat="server"></asp:textbox><br>         <asp:label  runat="server" width=           "74px">Password:</asp:label>         <asp:textbox  runat="server" width="156px"                    textmode="Password"></asp:textbox><br>       <br>         <asp:checkbox  runat="server" text="Remember Me">         </asp:checkbox><br>       <br>       <p>         <asp:label  runat="server"></asp:label>       </p>       <asp:button  runat="server" text="Log In"></asp:button>     </form>   </body> </html> 
Figure 13.1. Login page in browser.

graphics/13fig01.gif

The login page includes TextBox controls for User ID and Password. There is also a CheckBox control, labeled "Remember Me". This will be read during authentication to determine whether the user must log in on each visit.

For this site, the login page is not where the user intends to go. This example includes a startup page (see Figure 13.2), which was the original destination when the application began. This page (see Listing 13.2) can be assigned as the start page in the browser by right-clicking on the file, Default.aspx, and selecting Set as Start Page.

Listing 13.2 Main Page Code (Default.aspx)
 <%@ Page language="c#" Debug="true" Codebehind="Default.aspx.cs" AutoEventWireup="false" Inherits="Login.Default" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html>   <head>     <title></title>     <meta name="GENERATOR" content= "Borland ASP.NET Designer for c# Package Library 7.1">   </head>   <body ms_positioning="FlowLayout">     <form runat="server">       <h1>         Welcome to the Main Page!       </h1>     </form>   </body> </html> 
Figure 13.2. Main page in browser.

graphics/13fig02.gif

If the Web pages were set up like Listing 13.1 and Listing 13.2, the user would see the page in Figure 13.2 immediately. However, this example is set up to protect that page so that only authorized users may see it. The mechanism that makes this happen is a couple of sections in the web.config file that control authentication and authorization. Listing 13.3 contains the portions of the web.config file that make this happen. Remember, the web.config file is one of the files that C#Builder created automatically when the project was first created, and you can find it along with other project files in the Project Manager.

Listing 13.3 Authentication and Authorization for Users (web.config)
 <?xml version="1.0" encoding="utf-8" ?> <configuration>   <system.web>     <!--  Portions omitted for clarity.  -->       <authentication mode="Forms">         <forms loginUrl="Login.aspx">           <credentials passwordFormat="Clear">             <user name="Joe" password="abc123" />             <user name="May" password="def456" />           </credentials>         </forms>       </authentication>       <authorization>         <deny users="?"/>       </authorization>     <!--  Portions omitted for clarity.  -->   </system.web> </configuration> 

The mode attribute of the authentication element in the web.config file specifies the type of authentication being used for the application. It may be set to Windows, Passport, Forms, or None. In Listing 13.3, it is set to Forms to enable Forms-Based Authentication.

The credentials element enables Forms-Based Authentication to perform what is called URL authentication for an application. Its child elements may be either user or role, to authenticate individuals or groups of individuals, respectively. Listing 13.3 contains two user elements with name and password attributes representing the entries a user must make into the user ID and password fields on the login page. The Forms-Based Authentication process uses these credentials to determine whether a user is authorized to access application Web pages.

The other Forms-Based Authentication element in Listing 13.3 is the authorization element. The question mark in the users attribute represents anonymous users. Therefore the deny child element of the authorization element does not allow access to anonymous users. This is what causes requests for the main application page in Figure 13.2/Listing 13.2 to be redirected to the login page in Figure 13.1/Listing 13.1.

Possible child elements of the authorization element include allow and deny, described in Table 13.1. These child elements may have users, roles, or verbs attributes, shown in Table 13.2. The users and roles attributes may contain comma-delimited lists of individuals and groups, respectively, and the verbs attribute may contain a comma-delimited list of HTTP directives. The users element may contain special attribute symbols for identifying groups of people.

Table 13.1. Authorization Element Child Elements

ELEMENT NAME

PURPOSE

allow

List of items that are authorized to access Web pages

deny

List of items that may not access Web pages

Table 13.2 shows the available attributes for allow or deny elements that could be contained within an authorization element.

Table 13.2. Allow/Deny Element Attributes

ATTRIBUTE NAME

PURPOSE

users

Authorization rules for individuals

roles

Authorization rules for groups

verbs

Set of HTTP verbs, such as GET and POST, that may be used

Table 13.3 contains special attribute identities that may be used with any of the allow/deny attributes from Table 13.2.

Table 13.3. Special User Attribute Identities

IDENTITY SYMBOL

PURPOSE

?

Applies to Anonymous users

*

Applies to All users

The authorization element is what causes redirection to the login page, identified in the forms element of the authentication element (see Listing 13.3). However, unless there is additional logic in the Web application itself, the login page will be the only one the user sees. The user is authenticated and redirected to the page they originally wanted to see when they click the Log In button on the login page. Listing 13.4 shows how to perform this.

Listing 13.4 Authenticating User Credentials (Login.aspx.cs)
 using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.Security; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace Login {    /// <summary>    /// Summary description for WebForm1.    /// </summary>    public class Login : System.Web.UI.Page    {       protected System.Web.UI.WebControls.Label lblInfo;       protected System.Web.UI.WebControls.Label lblUserName;       protected System.Web.UI.WebControls.TextBox txtUserName;       protected System.Web.UI.WebControls.TextBox txtPassword;       protected System.Web.UI.WebControls.Label lblPassword;       protected System.Web.UI.WebControls.CheckBox cbxRememberMe;       protected System.Web.UI.WebControls.Button btnLogin;       protected System.Web.UI.WebControls.Label lblMessage;       private void Page_Load(object sender, System.EventArgs e)       {          // Put user code to initialize the page here       }       #region Web Form Designer generated code       override protected void OnInit(EventArgs e)       {          //          // CODEGEN: This call is required by the ASP.NET Web Form Designer.          //          InitializeComponent();          base.OnInit(e);       }       /// <summary>       /// Required method for Designer support - do not modify       /// the contents of this method with the code editor.       /// </summary>       private void InitializeComponent()       {          this.btnLogin.Click +=             new System.EventHandler(this.btnLogin_Click);          this.Load += new System.EventHandler(this.Page_Load);       }       #endregion       private void btnLogin_Click(object sender, System.EventArgs e)       {          if (FormsAuthentication.Authenticate(             txtUserName.Text, txtPassword.Text))          {             FormsAuthentication.RedirectFromLoginPage(                txtUserName.Text, cbxRememberMe.Checked);          }          else          {             lblMessage.Text = "Invalid Login!";          }       }    } } 

The FormsAuthentication class in the System.Web.Security namespace performs several functions that make working with Forms-Based Authentication easy. In Listing 13.4, the FormsAuthentication.Authenticate method uses information submitted in the txtUserName and txtPassword TextBox controls to authenticate the user. The Authenticate method is checking the credentials from the web.config file (see Listing 13.3) to validate that the user is who they say they are.

The FormsAuthentication.Authenticate method uses what is called URL authentication, by validating credentials against those listed in the web.config file. Although a web.config file would work for a very small site, it is not necessarily the most maintainable solution for large sites with many users. In that case, the best solution would be to replace the call to FormsAuthentication.Authenticate with a routine that authenticates via database lookups. Chapter 15, "ADO.NET and File I/O," discusses database access with ADO.NET.

If the user is authenticated, the method returns true and the algorithm calls the RedirectFromLoginPage method to let the user move on to the main application page, which they originally intended to visit. The parameters passed to RedirectFromLoginPage are the user ID and a persistent cookie indicator. The user ID is used for further authorization as the user visits more pages on the site. The persistent cookie indicator allows a login to persist across sessions. If this is false, the user must go through the login process for every session. Otherwise, the application recognizes the user on every visit, allowing them to visit pages without the need to log in.



C# Builder KickStart
C# Builder KickStart
ISBN: 672325896
EAN: N/A
Year: 2003
Pages: 165

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net