Lesson 3: Using Forms Authentication

Lesson 3: Using Forms Authentication

Forms authentication automatically displays a designated Web form to collect user name and password information. Code associated with that Web form authenticates and authorizes users based on a user list stored in the application s Web.config file or in a separate user database.

The advantage of Forms authentication is that users do not have to be member of a domain-based network to have access to your application. Another advantage is that many Web applications particularly commercial sites where customers order products want to have access to user information. Forms authentication makes these types of applications easier to create.

After this lesson, you will be able to

  • Activate Forms authentication for your Web application

  • Create a Web form to collect user name and password information

  • Authenticate users based on a user list stored in the application s Web.config file

  • Add new users and authenticate existing ones from a database

  • Limit access to specific locations

Estimated lesson time: 20 minutes

Enabling Forms Authentication

Forms authentication allows you to create your own database of users and validate the identity of those users when they visit your Web site.

To use Forms authentication to identify and authorize users, follow these steps:

  1. Set the authentication mode in Web.config to Forms.

  2. Create a Web form to collect logon information.

  3. Create a file or database to store user names and passwords.

  4. Write code to add new users to the user file or database.

  5. Write code to authenticate users against the user file or database.

When someone accesses a Web application that uses Forms authentication, ASP.NET displays the logon Web form specified in Web.config. Once a user is authorized, ASP.NET issues an authorization certificate in the form of a cookie that persists for an amount of time specified by the authentication settings in Web.config. Figure 8-11 illustrates the authentication process.

figure 8-11 forms authentication

Figure 8-11. Forms authentication

The difference between Windows authentication and Forms authentication is that in Forms authentication your application performs all the authentication and authorization tasks. You must create Web forms and write code to collect user names and passwords and to check those items against a list of authorized users.

The following sections describe how to implement Forms authentication in your application based on the general steps listed earlier in this section.

Setting the Forms Authentication Mode

You set an application s authentication mode in the Web.config file s <authorization> element. To set your application to use Forms authentication, make the following changes to the Web.config file:

<authentication mode="Forms" > <!-- Set authentication mode --> <forms loginUrl="LogIn.aspx" > <!-- Specify a log on form --> <credentials passwordFormat="Clear"> <!-- Create a user list --> <user name="Jesse" password="JuneBug"/> <user name="Linda" password="Liste"/> <user name="Henry" password="Henry"/> </credentials> </forms> </authentication> <authorization> <deny users="?" /> <! Deny all unauthenticated users --> </authorization>

The preceding Web.config fragment shows a simplified example of Forms authentication using most of the default settings and including a user list as part of the Web.config file. Table 8-2 lists all the possible attributes for the elements that make up the Forms authentication settings.

Table 8-2. Forms Authentication Settings in Web.config

Element

Attribute

Description

<authentication>

mode

Set to Forms to enable Forms authentication.

<forms>

name

Use to set the name of the cookie in which to store the user s credential. The default is .authaspx. If more than one application on the server is using Forms authentication, you need to specify a unique cookie name for each application.

loginUrl

Use to set the name of the Web form to display if the user has not already been authenticated. If omitted, the default is Default.aspx.

protection

Use to set how ASP.NET protects the authentication cookie stored on the user s machine. The default is All, which performs encryption and data validation. Other possible settings are Encryption, Validation, and None.

timeout

Use to set the number of minutes the authentication cookie persists on the user s machine. The default is 30, indicating 30 minutes. ASP.NET renews the cookie automatically if it receives a request from the user and more than half of the allotted time has expired.

path

Use to set the path used to store the cookie on the user s machine. The default is a backslash (\).

<credentials>

passwordFormat

Use to set the algorithm used to encrypt the user s password. The default is SHA1. Other possible settings are MD5 and Clear (which prevents encryption).

<users>

name

Use to set the name of the user.

password

Use to set the password for the user.

The <credentials> element allows you to store your user list in the Web.config file. That is convenient for simple authentication, where an administrator adds new users and sets their passwords, but it s not the best approach if you allow users to set up their own accounts or maintain their own passwords.

In those cases, you will want to create a users file or a users database to store user names and encrypted passwords. Using a database has the added benefit of allowing you to store all sorts of additional information about the user, such as shipping address and order history.

The following section shows how to authenticate users using credentials stored in Web.config. The subsequent sections show the more advanced (and more complicated) approach of using a user database.

Creating a LogIn Web Form

To authenticate users through Forms authentication, you need to create a Web form that allows users to log on. This Web form is identified by name in the <forms> element of Web.config.

The login Web form can be as simple as a pair of text boxes and a Button control, or it can appear on a page containing other, nonsecure content. For example, you can include logon fields on an application home page, as shown in Figure 8-12.

figure 8-12 login fields on an application home page

Figure 8-12. Login fields on an application home page

When the user clicks Sign On, the application authenticates the user name and password, issues an authentication certificate, and allows access to the rest of the application, as shown in the following code:

Visual Basic .NET

' Add at module-level. Imports System.Web.Security Private Sub butSignOn_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles butSignOn.Click ' Authenticate username/password from <credentials>. If FormsAuthentication.Authenticate(txtUserName.Text, txtPassword.Text) _ Then ' If found, display the application's Start page. FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, True) Else ' Otherwise, clear the password. txtPassword.Text = "" ' If third try, display "Access Denied" page. If CInt(ViewState("Tries")) > 1 Then Response.Redirect("Denied.htm") Else ' Otherwise, increment number of tries. ViewState("Tries") = CInt(ViewState("Tries")) + 1 End If End If End Sub

Visual C#

// Add at module-level. using System.Web.Security; private void butSignOn_Click(object sender, System.EventArgs e) { // Authenticate username/password from <credentials>. if (FormsAuthentication.Authenticate(txtUserName.Text, txtPassword.Text)) // If found, display the application's Start page. FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, true); else { // Otherwise, clear the password. txtPassword.Text = ""; // If third try, display "Access Denied" page. if (System.Convert.ToInt32(ViewState["Tries"]) > 1) Response.Redirect("Denied.htm"); else // Otherwise, increment number of tries. ViewState["Tries"] = System.Convert.ToInt32(ViewState["Tries"]) + 1; } }

There are a few important things to note about the preceding code:

  • The FormsAuthentication class is part of the System.Web.Security namespace, so you must include that namespace using the Visual Basic .NET Imports statement or the Visual C# using statement, or the fully qualified references to the class.

  • The FormsAuthentication class s Authenticate method checks the user name and password against the user list found in the <credentials> element of Web.config.

  • The FormsAuthentication class s RedirectFromLoginPage method displays the application s start page. If the logon fields appear on the application s start page, you should disable them or otherwise indicate a successful logon.

  • If the user name and password aren t valid, the code lets the user have two more tries before displaying an Access Denied page. That page is an HTML page rather than a Web form, since access to any Web forms in the application is also denied. If you redirect users to another page in this way, make sure that the page is outside the scope of the application.

Use the FormsAuthentication class to sign out when the user has finished with the application or when you want to remove the authentication cookie from his or her machine. For example, the following code ends the user s access to an application and requires him or her to sign back in to regain access:

Visual Basic .NET

Imports System.Web.Security Private Sub butSignOut_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles butSignOut.Click ' Remove authentication cookie. FormsAuthentication.SignOut() ' Redirect back to this page (displays log in screen). Response.Redirect("UserInfo.aspx") End Sub

Visual C#

using System.Web.Security; private void butSignOut_Click(object sender, System.EventArgs e) { // Remove authentication cookie. FormsAuthentication.SignOut(); // Redirect back to this page (displays log in screen). Response.Redirect("UserInfo.aspx"); }

Authenticating Users with a Database

The preceding sections showed how to authenticate users based on a list in Web.config. The FormsAuthentication class s Authenticate method is set up to read from that file automatically. That s fine if user names and passwords are created and maintained by a system administrator, but if you allow users to create their own user names or change their passwords, you ll need to store that information outside the Web.config file. This is because changing Web.config at run time causes the Web application to restart, which resets any Application state and Session state variables used by the application.

You can store user names and passwords in any type of file; however, using a database has the following significant advantages:

  • User names can be used as primary keys to store other information about the user.

  • Databases can provide high performance for accessing user names and passwords.

  • Adding, modifying, and accessing records are standardized through SQL.

When storing user names and passwords in a file or database, you have the option of encrypting them using the FormsAuthentication class s HashPasswordForStoringInConfigFile method. This uses the SHA1 or MD5 algorithms to encrypt data, as shown here:

Visual Basic .NET

' Encrypt the password. Password = FormsAuthentication.HashPasswordForStoringInConfigFile(Password, _  "SHA1")

Visual C#

Password = FormsAuthentication.HashPasswordForStoringInConfigFile(Password,  "SHA1");

The following sections show how to add new user names and passwords to a simple database and how to use that database to authenticate users.

Adding Users to a Database

To add users to a database, collect the user name and password from two TextBox controls and provide an event procedure to add the user that displays a message indicating whether the user was added. The following event procedure calls the helper function AddUser to add the user name and password to the database:

Visual Basic .NET

Private Sub butNewUser_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles butNewUser.Click If AddUser(txtUserName.Text, txtPassword.Text) Then spnNote.InnerText = "User added." Else spnNote.InnerText = "User exists. Choose a different user name." End If End Sub

Visual C#

private void butNewUser_Click(object sender, System.EventArgs e) { if (AddUser(txtUserName.Text, txtPassword.Text)) spnNote.InnerText = "User added."; else spnNote.InnerText = "User exists. Choose a different user name."; }

The AddUser helper function shown in the following code encrypts the password before storing the user name and password in a database using the SQL INSERT command. If the user name already exists in the database, the exception-handling block catches the error and returns False to indicate that the user was not added.

Visual Basic .NET

Private Function AddUser(ByVal UserName As String, ByVal Password_ As String) As Boolean ' Declare variable to track success/failure. Dim bSuccess As Boolean ' Encrypt the password. Password = _ FormsAuthentication.HashPasswordForStoringInConfigFile(Password, _  "SHA1") ' Create command to insert user name and password. Dim oleCommand As New OleDbCommand("INSERT INTO Users" + _  " VALUES('" + UserName + "', '" + Password + "')", oledbUsers) ' Catch errors in case record already exists. Try ' Open the database connection. oledbUsers.Open() ' If record added, set success to true. If oleCommand.ExecuteNonQuery() Then bSuccess = True ' Close connection. oledbUsers.Close() Catch ' Otherwise, success if false. bSuccess = False ' Close connection. oledbUsers.Close() End Try ' Return success/failure. Return bSuccess End Function

Visual C#

private bool AddUser(string UserName, string Password) { // Declare variable to track success/failure. bool bSuccess = false; // Encrypt the password. Password = FormsAuthentication.HashPasswordForStoringInConfigFile (Password, "SHA1"); // Create command to insert user name and password. OleDbCommand oleCommand = new OleDbCommand("INSERT INTO Users" +  " VALUES('" + UserName + "', '" + Password + "')", oledbUsers); // Catch errors in case record already exists. try { // Open the database connection. oledbUsers.Open(); // If record added, set success to true. if (oleCommand.ExecuteNonQuery() != 0) { bSuccess = true; // Close connection. oledbUsers.Close(); } } catch { // Otherwise, success if false. bSuccess = false; // Close connection. oledbUsers.Close(); } // Return success/failure. return bSuccess; }

Authenticating Users from a Database

When you authenticate users from Web.config, you use the Authenticate method. When you authenticate users from a database, you must write your own code to find and compare user names and passwords. The following event procedure uses the CheckPassword helper function to validate the user name and password text boxes before authenticating the user and allowing access to the application:

Visual Basic .NET

Private Sub butSignOn_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles butSignOn.Click ' If user name and password are found, ' authorize the user and show start page. If CheckPassword(txtUserName.Text, txtPassword.Text) Then FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, True) Else ' Display message. spnNote.InnerText = "User name or password not found. Try again." ' Allow three tries to log in. ViewState("tries") = ViewState("tries") + 1 If ViewState("tries") > 3 Then Response.Redirect("Denied.htm") End If End If End Sub

Visual C#

private void butSignOn_Click(object sender, System.EventArgs e) { // Authenticate username/password from <credentials>. if (CheckPassword(txtUserName.Text, txtPassword.Text)) // If found, display the application's Start page. FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, true); else { // Otherwise, clear the password. txtPassword.Text = ""; // Display message. spnNote.InnerText = "User name or password not found. Try again."; // If third try, display "Access Denied" page. if (System.Convert.ToInt32(ViewState["Tries"]) > 1) Response.Redirect("Denied.htm"); else { // Otherwise, increment number of tries. ViewState["Tries"] = System.Convert.ToInt32(ViewState["Tries"]) + 1; if (System.Convert.ToInt32(ViewState["Tries"]) > 3) Response.Redirect("Denied.htm"); } } }

The CheckPassword helper function shown in the following code encrypts the password, finds the database record based on the user name, and compares the encrypted password against the password found in the database. Access to the database is performed within an exception-handling block to prevent locking conflicts from displaying errors to the user.

Visual Basic .NET

Private Function CheckPassword(ByVal UserName As String, _ ByVal Password As String) As Boolean ' Declare variable to track success/failure. Dim bSuccess As Boolean ' Encrypt the password. Password = _ FormsAuthentication.HashPasswordForStoringInConfigFile(Password, _  "SHA1") ' Create command to get row from users table based on UserName. Dim oleCommand As New OleDbCommand("SELECT * FROM Users" + _  " WHERE UserName='" + txtUserName.Text + "'", oledbUsers) ' Check for errors using database Try ' Open the database connection. oledbUsers.Open() ' Get the author ID. Dim rdrUsers As OleDbDataReader = oleCommand.ExecuteReader() While rdrUsers.Read() If Password = rdrUsers.Item("Password") Then bSuccess = True End While ' Close connection. oledbUsers.Close() Catch ' Otherwise set failure. bSuccess = False ' Close connection. oledbUsers.Close() End Try Return bSuccess End Function

Visual C#

private bool CheckPassword(string UserName, string Password) { // Declare variable to track success/failure. bool bSuccess = false; // Encrypt the password. Password = FormsAuthentication.HashPasswordForStoringInConfigFile(Password,  "SHA1"); // Create command to get row from users table based on UserName. OleDbCommand oleCommand = new OleDbCommand("SELECT * FROM Users" +  " WHERE UserName='" + txtUserName.Text + "'", oledbUsers); // Check for errors using database try { // Open the database connection. oledbUsers.Open(); // Get the author ID. OleDbDataReader rdrUsers = oleCommand.ExecuteReader(); while (rdrUsers.Read()) { if (Password == rdrUsers["Password"].ToString()) bSuccess = true; } // Close connection. oledbUsers.Close(); } catch { // Otherwise set failure. bSuccess = false; // Close connection. oledbUsers.Close(); } return bSuccess; }

Controlling Access to Specific Locations

The authorization settings in the Web.config file apply hierarchically within the folder structure of a Web application. For instance, you might want to allow all users access to the root folder of a Web application but restrict access to Web forms (and tasks) available from a subfolder. To do this, set the authentication type in the root folder s Web.config file, and then use the <authorization> element in the subfolder s Web.config file to restrict access.

In the following Web.config settings, the root folder settings allow all users access and the /Restricted folder s Web.config file allows access only to Henry:

<!-- From Web.config in application's root folder --> <configuration> <system.web> <authentication mode="Forms" > <!-- Set authentication mode --> <forms loginUrl="LogIn.aspx" > <!-- Specify a log on form --> <credentials passwordFormat="Clear"><!-- Create a user list --> <user name="Jesse" password="JuneBug"/> <user name="Linda" password="Leste"/> <user name="Henry" password="Henry" /> </credentials> </forms> </authentication> <authorization> <allow users="*" /> <!-- Allow all users --> </authorization> </system.web> </configuration> <!-- From Web.config in /Restricted folder --> <configuration> <system.web> <authorization> <allow users="Henry" /> <!-- Allow Henry --> <deny users="*" /> <!-- Deny everyone else --> </authorization> </system.web> </configuration>

When you run a Web application with the preceding Web.config settings, users are not authenticated until they request a resource from the /Restricted folder. When a user requests a Web form from the /Restricted folder, the LogIn.aspx Web form is displayed and the user is authenticated.

NOTE
Authentication type (Windows, Forms, or Passport) can be set only at the application s root folder. To change authentication type in a subfolder, you must create a new Web application project and application starting point for that subfolder.



MCAD(s)MCSD Self-Paced Training Kit(c) Developing Web Applications With Microsoft Visual Basic. Net and Microsoft V[.  .. ]0-315
MCAD(s)MCSD Self-Paced Training Kit(c) Developing Web Applications With Microsoft Visual Basic. Net and Microsoft V[. .. ]0-315
ISBN: N/A
EAN: N/A
Year: 2003
Pages: 118

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