ONDotNet.com    
 Published on ONDotNet.com (http://www.ondotnet.com/)
 See this if you're having trouble printing code examples


Using the Security Controls in ASP.NET Whidbey

by Wei-Meng Lee
01/05/2004

In ASP.NET 1.1, you can use form-based authentication to authenticate web users through the use of a custom login page. While this is a useful and straightforward technique, it still requires you to write your own code to perform the authentication, most often through the use of SQL Server. However, this mundane task has been reduced greatly by the introduction of new security controls in ASP.NET Whidbey. In this article, I will illustrate how to use the various security controls that comes with ASP.NET Whidbey to help in the securing of your web resources.

Creating a Login Page

Let's first take a look at how to create a simple web site that authenticates users using the built-in security controls. Launch Visual Studio .NET Whidbey, create a new web site, and name it "Membership." Rename the default.aspx Web form to main.aspx. Add a web.config file by right-clicking on the web site name in Solution Explorer and selecting Add New Item (see Figure 1).


Figure 1. Adding a new web.config file to the web site

Modify the web.config file by adding the following lines (shown in bold). This will change the authentication mode from the default "Windows" to "Forms." The web form to be used for authentication is named login.aspx:


<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
   <system.web>
     <compilation debug="false" />
     <authentication mode="Forms">
        <forms name=".ASPXAUTH" 
               loginUrl="login.aspx" 
               protection="Validation" 
               timeout="999999" />
     </authentication>
     <roleManager enabled="true">
        <providers/> 
     </roleManager>
     <globalization requestEncoding="utf-8" responseEncoding="utf-8" />
   </system.web>
</configuration>

The Membership Provider used in this case is the default one that uses Microsoft Access to store the users' information. Eventually, Whidbey will also include the following Membership Providers:

We will discuss the Access database later in this article. In the Toolbox, you will see the various security controls under the Security tab (see Figure 2):


Figure 2. The security controls in ASP.NET Whidbey

Populate the main.aspx web form with the following controls (see Figure 3):


Figure 3. Populating the web form with the LoginStatus and LoginView controls

The LoginStatus control displays a hyperlink that shows "Login" when the user is un-authenticated, and "Logout" when the user is logged in. The LoginView control is a container that displays different information depending on whether the user is logged in or not. Configure the LoginView control by clicking on it and selecting the Edit Templates link (see Figure 4):


Figure 4. Editing the LoginView control

There are two templates you can configure: AnonymousTemplate and LoggedInTemplate. Change the Display drop-down box to AnonymousTemplate and key the text (as shown in Figure 5) into the LoginView control:


Figure 5. Editing the AnonymousTemplate

Likewise, change the Display drop-down box to LoggedInTemplate and key the text (as shown in Figure 6) into the LoginView control. Also, drag and drop the LoginName control into the LoginView control:


Figure 6. Editing the LoggedIn Template

Click on End Template Editing to complete the editing of the LoginView control. You should see something like Figure 7:


Figure 7. Viewing the LoginView control

Now that you have created the web.config file and populated the web form, let's add a new web form and name it login.aspx. On this web form, drag and drop a Login control (see Figure 8). You can click on Auto Format... to change the layout of the control:


Figure 8. Using the Login control

Adding a New User

Before you test your application, you need to add a user to your application so that you can test out the authentication process. For this, we will use the ASP.NET Configuration tool (found in the Website->ASP.NET Configuration menu item) (see Figure 9):


Figure 9. Launching the ASP.NET configuration tool

To create a new user, click on the Security tab (see Figure 10):


Figure 10. The ASP.NET configuration tool

Choose the Security Management option and click Next (see Figure 11).


Figure 11. Choosing the security management method

Under the Users heading, click on Create User to create a new user account (see Figure 12):


Figure 12. Creating a new user

Enter the required information. You can leave out the non-essential information (those text fields without asterisks) (see Figure 13). Click Done to complete the account's creation.


Figure 13. Entering information for a new user

Testing the Application

You are now finally ready to test drive your application. In Solution Explorer, select main.aspx and press Ctrl-F5 (start without debugging). You should see the following (see Figure 14):


Figure 14. The opening page: not logged in yet

Click on the Login link to go to the login.aspx page. Enter the account details of the account just created and click Log In (see Figure 15):


Figure 15. Logging in

If the account is authenticated, you should see the following (see Figure 16):


Figure 16. User authenticated

Restricting Access to Pages

The last section showed you how to use the Login control for getting a user's credentials. In this section, I will show how you can restrict access to certain pages based on the user's credentials. In the current web site, create a new folder named Private. Add a new page to this folder and name it privatepage1.aspx. Add a web.config file and insert the following:

<authorization>
	 <deny users="?" />
</authorization>

The <deny> element specifies to which users to deny access to the current folder (Private, in this case). You can also use the <allow> element to specifically state which users have access to the current folder. The ? means anonymous users, or non-authenticated users, while * means all users.

Your Solution Explorer should now look like this (see Figure 17):


Figure 17. The Solution Explorer

If you now try to access the privatepage1.aspx page using the URL http://localhost:40967/Membership/Private/privatepage1.aspx, you will be redirected to the login.aspx page. Only when a user is authenticated will this page be accessible.

Creating Roles

Besides restricting access to individual users, it is sometimes much easier to restrict access based on groups, or roles. You can create roles using the ASP.NET Configuration Tool. Click on Create Roles to create a new role (see Figure 18):


Figure 18. Creating a new role

Enter a name for this new role. In my case, I named it "administrator." Click on Done to complete the role's creation (see Figure 19).


Figure 19. Naming a new role

To add/remove users from a role, click on the Manage link (see Figure 20):


Figure 20. Managing a role

Check the user that is going to be part of this role (see Figure 21)


Figure 21. Assigning a user to a role

So now "lwm" is a member of the administrator role. If you add the following line to web.config, only users belonging to the administrator role can now access the page.


<authorization>
	 <allow roles="administrator" />
	 <deny users="*" />
</authorization>

To test this example, you need to go to main.aspx and log in with the account information. Then go to http://localhost:40967/Membership/Private/privatepage1.aspx. If your user ID is part of the administrator role, you can then view the page; otherwise, you will see an error page.

Retrieving Forgotten Passwords

Another security control that we have not discussed yet is the PasswordRecovery control (see Figure 22). This control allows users to retrieve their forgotten passwords via email. All you have to do to use this control is to set two properties and configure a SMTP server for sending emails to the user.


Figure 22. Using the PasswordRecovery control

To send out emails to users, you just need to set the From and Subject properties from the MailDefinition node in the Properties window (see Figure 23).


Figure 23. Configuring the PasswordRecovery control

Adding a User Via the Membership Class

The last topic I want to discuss in this article is the Membership class. The Membership class allows you to perform common tasks involved in user management, such as user addition, deletion, change of passwords, etc. To see how to use the Membership class, add a new web form and name it AddUser.aspx. Populate the new web form with the following controls, as shown in Figure 24:


Figure 24. Populating the web form

In the Click event of the Add User button, code the following:

using System.Web.Security;

void cmdAddUser_Click(object sender, System.EventArgs e)
{
  // can also use the CompareValidator control
  if (txtPassword1.Text==txtPassword2.Text) 
    Membership.CreateUser(txtUserID.Text, 
                          txtPassword1.Text, 
                          txtEmail.Text);
}

To test the application, go to http://localhost:28169/Membership/Private/AddUser.aspx and add a new user. You can verify that the new user has been added by viewing the AspNetDB file located in your application's Data folder. The user information is saved in the aspnet_Users and aspMembership tables.

Wei-Meng Lee (Microsoft MVP) http://weimenglee.blogspot.com is a technologist and founder of Developer Learning Solutions http://www.developerlearningsolutions.com, a technology company specializing in hands-on training on the latest Microsoft technologies.


Return to ONDotnet.com

Copyright © 2009 O'Reilly Media, Inc.