Section 4.9. Easily Authenticate Users

4.9. Easily Authenticate Users

In ASP.NET 1.0 and 1.1, developers had a handy tool called forms authentication. Essentially, forms authentication kept track of which users had logged in by using a special cookie. If ASP.NET noticed a user who hadn't logged in trying to access a secured page, it automatically redirected the user to your custom login page.

Note: Tired or writing your own authentication code? ASP. NET 2.0 will take care of the drudgery, maintaining user credentials in a database and validating a user login when you ask for it.

On its own, forms authentication worked well, but it still required some work on your part. For example, you needed to create the login page and write the code that examined the user's login name and password and compared it to values in a custom database. Depending on how your application worked, you may also have needed to write code for adding new users and removing old ones. This code wasn't complicated, but it could be tedious.

ASP.NET 2.0 dramatically reduces your work with its new membership features. Essentially, all you need to do is use the methods of the membership classes to create, delete, and validate user information. ASP.NET automatically maintains a database of user information behind the scenes on your behalf.

4.9.1. How do I do that?

The first step in adding authentication to your site is to choose a membership provider, which determines where the user information will be stored. ASP.NET includes membership providers that allow you to connect to a SQL Server database, and several additional providers are planned.

The membership provider is specified in the web.config configuration file. However, rather than typing this information in by hand, you'll almost certainly use the WAT, described in the lab "Administer a Web Application." Just click the Security tab, and click the "Use the security Setup Wizard" link to walk through a wizard that gives you all the options you need. The first question is the access methodin other words, how your visitors will authenticate themselves. Choose "From the internet" to use forms authentication rather than Windows authentication.

The following step allows you to choose the membership provider. You can choose a single provider to use for all ASP.NET features, or separate providers for different features (such as membership, role-based security, and so on). If you choose to use a SQL Server database, you must also run the aspnet_regsql.exe utility, which will walk you through the steps needed to install the membership database. You'll find the aspnet_regsql.exe utility in the c:\[WinDir]\Microsoft.NETramework\[Version] directory.

Next, you'll have the chance to create users and roles. Roles are discussed in a later lab ("Use Role-Based Authentication"), so you don't need to create them yet. You don't need to create a test user, because you'll do that through your web site in the next step.

You can choose the name of your login page by modifying the <authentication> section in the web.config file, as shown here:

<?xml version="1.0"?> <configuration>   <system.web>     <authentication mode="Forms">       <forms loginUrl="Login.aspx" />     </authentication>         <!-- Other settings ommitted. -->   </system.web> </configuration>

In this case, the login page for the application is named Login.aspx (which is the default). In this page, you can use the shared methods and properties of the System.Web.Security.Membership class to authenticate your users. However, you don't need to, because ASP.NET includes a set of security-related controls that you can drag and drop into your web pages effortlessly. The security controls include:


Shows the controls needed for a user to log in, including username and password text boxes, and a Login button. Optionally, you can show an email address text box, and you can configure all the text labels in the control by modifying properties like UserNameLabelText and PasswordLabelText.


Shows one template out of a group of templates, depending on who is currently logged in. This gives you a way to customize content for different users and roles without using any custom code.


Provides a mechanism through which users can have a forgotten password mailed to them. This feature is disabled by default and requires some tweaking of web.config settings.


Displays a Login link if the user isn't currently logged in, or a Logout link if the user is logged in.


Shows the name of the currently logged-in user in a label.


Allows the user to step through creating a new user account.


Allows the user to change his or her current password, by specifying the current and new passwords.

You'll find the security controls in the Login tab of the Visual Studio toolbox. To try them out, create a new page named RegisterUser.aspx. Drop a CreateUserWizard control onto the web page. Now run the page and use the wizard to create a new user with the username testuser and the password test.

By default, the CreateUserWizard control uses two steps (shown in Figure 4-12). The first step allows you to specify all your user information, and the second step simply displays a confirmation message.

Figure 4-12. Adding a new user with the CreateUserWizard control

If you like, you can dig into the backend database to confirm that your user information was saved (after all, it happened automatically, without requiring any custom code). But a better test is to actually create a restricted area of your web page.

First, add the Login.aspx page. To create this page, just drag a Login control onto the page, and you're finished.

Now, it's time to restrict access to a portion of the web site. Select Website New Folder to create a subdirectory in your web application directory, and name the new directory Secured. Next, create a new page in this directory named Private.aspx, and add the text "This is a secured page."

Now, run the WAT by selecting Website ASP.NET Configuration. Choose the Security tab. Using this tab, you can examine the list of users (including the test user you added in the previous step) and modify their information. What you really need to do, however, is click the "Create access rules" link to restrict access to the Secured directory. Select the directory in the list, choose the Deny Permission option, and select Anonymous users, as shown in Figure 4-13. Then, click OK to add this rule.

Figure 4-13. Creating a rule to prevent anonymous access to the Secured directory

Now you're ready to test this simple security example. Right-click on the Private.aspx, file and choose "Set As Start Page." Then, run your application. ASP.NET will immediately detect that your request is for a secured page and you haven't authenticated yourself. Because you've configured forms authentication, it redirects you to the Login.aspx page.

Now enter the username testuser and the password test in the login control. ASP.NET will validate you using the membership provider and redirect you to the originally requested Private.aspx page.

In other words, by using the CreateUserWizard and Login controls in conjunction with the WAT, you've created an authentication system that restricts access to a specific portion of your web siteall without a single line of code.

4.9.2. What about...

...ways to customize the authentication process? If you need to control how authentication, user creation, and other security tasks work, you'll be happy to find that the security controls are easily extensible. You can add new steps to the CreateUserWizard to collect additional data, respond to events that fire when the user is logged in (or denied access), and even convert the steps to editable templates so that you can fine-tune the user interface, adding new controls or removing existing ones.

If you want to go a step further, you can abandon the security controls altogether, but still create almost no-code solutions using the static methods of the System.Web.Security.Membership class. Here are some of the methods you can call:

CreateUser( )

Creates a new user record in the data store with a username, a password, and (optionally) an email address.

DeleteUser( )

Removes the user record from the data store that has the indicated username.

GeneratePassword( )

Creates a random password of the specified length. You can suggest this to the user as a default password when creating a new user record.

GetUser( )

GetUser( ) retrieves a MembershipUser record for a user with the given username. You can then examine the MembershipUser properties to find out details such as the user's email address, when the account was created, when the user last logged in, and so on. If you don't specify a username, the GetUser( ) method retrieves the current user for the page.

GetUserNameByEmail( )

If you know a user's email address but you don't know the username, you can use this method to get it.

UpdateUser( )

After you've retrieved a MembershipUser object, you can modify its properties and then submit the object to the UpdateUser( ) method, which commits all your changes to the user database.

ValidateUser( )

This accepts a username and password, and verifies that it matches the information in the database (in which case it returns true). ASP.NET doesn't actually store the unencrypted password in the databaseinstead, it uses a hashing algorithm to protect this information.

Using these methods, you can quickly construct basic login and user registration pages without needing to write any database code. All you need to do is create the user interface for the page (in other words, add labels, text boxes, and other controls).

For example, to design a customized login page, just create a page with two text boxes (named txtUser and txtPassword) and a button (named cmdLogin). When the button is clicked, run this code:

Sub cmdLogin_Click(ByVal sender As Object, ByVal e As System.EventArgs)          If Membership.ValidateUser(txtUser.Text, txtPassword.Text) Then         ' ASP.NET validated the username and password.             ' Send the user to page that was originally requested.         FormsAuthentication.RedirectFromLoginPage(txtUser.Text, False)     Else         ' The user's information is incorrect.             ' Do nothing (or just display an error message).     End If      End Sub

Notice how simple the code is for this page. Instead of manually validating the user by connecting to a database, reading a record, and checking the fields, this code simply calls the Membership.ValidateUser( ) method, and ASP.NET takes care of the rest.

Just as easily, you can create a page that generates a new user record with the Membership class:

Sub cmdRegister_Click(ByVal sender As Object, ByVal e As System.EventArgs)          Dim Status As MembershipCreateStatus     Dim NewUser As MembershipUser = Membership.CreateUser(_       txtUser.Text, txtPassword.Text, txtEmail.Text, Status)          ' If the user was created successfully, redirect to the login page.      If Status = MembershipCreateStatus.Success Then         Response.Redirect("Login.aspx")     Else         ' Display an error message in a label.         lblStatus.Text = "Attempt to create user failed with error " & _           Status.ToString( )     End If      End Sub

For more information, look up the index entry "Membership class" in the MSDN Help. You can also refer to the next three labs, which build up the basic membership framework with new features:

"Determine How Many People Are Currently Using Your Web Site"

Explains how additional membership features can track who's online.

"Use Role-Based Authorization"

Describes how you can enhance your authorization logic by assigning users to specific roles, essentially giving them different sets of privileges. This feature isn't handled by the membership service, but by a complementary role manager service.

"Store Personalized Information"

Shows how you can store other types of user-specific information in a data store, instead of just usernames, passwords, and email addresses. This feature isn't handled by the membership service, but by a complementary personalization service.

Visual Basic 2005(c) A Developer's Notebook
Visual Basic 2005: A Developers Notebook
ISBN: 0596007264
EAN: 2147483647
Year: 2006
Pages: 123

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: