Custom Form-Based Authentication in ASP.NET
 
Published: 14 Dec 2005
Unedited - Community Contributed
Abstract
If you have built a web application with classic ASP or even .NET 1.1, you know the amount of effort that went into creating form-based authentication. You pretty much had to do accomplish every tedious task such as building the login form and performing validation just to name a couple. If you wanted to utilize role-based management in an application, you had to write even more code! With the release of .NET 2.0 these days are behind us. Join Steven as he explains how to take advantage of these features in ASP.NET 2.0.
by Steven Swafford
Feedback
Average Rating: 
Views (Total / Last 10 Days): 34512/ 47

Introduction

[Download Sample Code]

Have you ever been in a position where you were required to integrate authentication into your Web application? If the Web application is for the intranet, this is typically a simple process: just enable Windows authentication within IIS. More often than not this is typically not a luxury that we have in the case of more common internet Web applications, and when you take into account the volume of potential users of internet Web applications, custom form-based authentication is the only scalable solution.

For those of you who wrote code in classic ASP, accomplishing such a task was at times overwhelming. Then along came .NET 1.x, which of course makes such a task simpler; however, there was still much to accomplish when it came to form-based authentication. With the recent RTM of .NET 2.0 and the combination of Visual Studio .NET 2005, these days are over. With little or no effort you can accomplish form-based authentication in no time.

The purpose of this article is to introduce the simplicity of the following:

  1. Membership Management
  2. Preparing Your SQL Server Database
  3. Security Server Controls
  4. Role Management

Figure 1: Simple Authentication State Diagram

As you can see in the above diagram, when a user enters the application, two possible courses of action occur.

  1. The user is authenticated, so the requested content is returned.
  2. The user is not authenticated and is sent to a registration form. Once the registration process is successful, then and only then is the requested content returned.
Membership API

The foundation of the Membership API is the Membership class. The following are some of the most commonly used methods of the Membership class:

  1. CreateUser: Used to create a new user.
  2. GetUser: Gets the details of a particular user. Returns an instance of the MembershipUser (Sys-tem.Web.Security.MembershipUser) type.
  3. UpdateUser: Updates user details in the user credentials store. This method accepts an instance of the MembershipUser type.
  4. ValidateUser: Takes a user's credentials (username and password) and returns true if the credentials are valid, and false if they are not.

I highly recommend that you take the time to read the background material, Introduction to Membership, if have not previously done so.

Prepare Your SQL Server Database

The first step you should take is to set up your database so that you can begin to work with the Membership API. This is a simple task thanks in large part to the GUI interface that ships with the .NET 2.0 framework. For those of you die-hard command-line junkies, there is no need to worry, just run aspnet_regsql.exe with the command line switch /?, and youre all set. For those who prefer the GUI interface, simply run aspnet_regsql.exe from a command prompt or the run window within Windows. By default this tools starts in wizard mode.

Figure 2: ASP.NET SQL Server Setup Wizard

Figure 3: Select a Setup Option

Figure 4: Select the Server and Database

Figure 5: Confirm Your Settings

As you can gather, this takes very little effort on our part, and to drive home the point, here is a screenshot of a database after I ran this wizard.

Figure 6: Example Database Schema

At this point, your database has been prepared, and you are now ready to move on to the Visual Studio .NET 2005 IDE and create a registration page without writing a single line of code. One point I need to make is that you need to modify your web.config to point to the database that you have just provisioned.

Listing 1: Example SQL Server Connection String

<remove name="LocalSqlServer" />

<add name="LocalSqlServer"

  providerName="System.Data.SqlClient"

  connectionString="server=servername;uid=userid;pwd=password;database=databasename"/>

Create the Default Registration, Login, and PasswordRetrieval Web Forms

Within your IDE, create the following Web forms and name them Registration.aspx, Login.aspx, and PasswordRecovery.aspx. Without writing any code, all you have to do is drag and drop the CreateUserWizard, Login, and PasswordRecovery controls from your toolbox onto the respective web form.

Figure 7: CreateUserWizard Control

Figure 8: Login Control

Figure 9: PasswordRecovery Control

At this point, it would worth mentioning the configuration behind this control is located in the machine.config file located within your .NET 2.0 framework installation directory (C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG). If you open machine.config and look for the entry AspNetSqlMembershipProvider within the Membership node you will find the settings associated to creating new user accounts.

Listing 2: Default AspNetSqlMembershipProvider Settings

<add name="AspNetSqlMembershipProvider"

  type="System.Web.Security.SqlMembershipProvider,

        System.Web, Version=2.0.0.0, Culture=neutral,

        PublicKeyToken=b03f5f7f11d50a3a"

  connectionStringName="LocalSqlServer"

  enablePasswordRetrieval="false"

  enablePasswordReset="true"

  requiresQuestionAndAnswer="true"

  applicationName="/"

  requiresUniqueEmail="false"

  passwordFormat="Hashed"

  maxInvalidPasswordAttempts="5"

  minRequiredPasswordLength="7"

  minRequiredNonalphanumericCharacters="1"

  passwordAttemptWindow="10"

  passwordStrengthRegularExpression="" />

Now that I have touched on customizing the AspNetSqlMembershipProvider, let us now return to the Web forms we previously created and register a new user. As you will see, we have provided the capability for users to create an account, recover a forgotten password, and, finally, the login functionality all within a matter of minutes.

Membership Customization

As I previously demonstrated, creating these Web forms is simple and painless; however, what if you want to customize the functionally behind these Web forms? This also is a straightforward process, but there is a little more effort required on your part. Use the web.config file to customize the settings. Take a look a Listing 3 below.

Listing 3: Custom AspNetSqlMembershipProvider Settings

<membership>

  <providers>

    <remove name="AspNetSqlMembershipProvider"/>

    <add name="AspNetSqlMembershipProvider"

      type="System.Web.Security.SqlMembershipProvider,

            System.Web, Version=2.0.0.0, Culture=neutral,

            PublicKeyToken=b03f5f7f11d50a3a"

      connectionStringName="LocalSqlServer"

      enablePasswordRetrieval="true"

      enablePasswordReset="true"

      requiresQuestionAndAnswer="false"

      applicationName="/"

      requiresUniqueEmail="true"

      passwordFormat="Encrypted"

      maxInvalidPasswordAttempts="3"

      minRequiredPasswordLength="6"

      minRequiredNonalphanumericCharacters="2"

      passwordAttemptWindow="10"

      passwordStrengthRegularExpression="" />

  </providers>

</membership>

The customization I am referring to is:

  1. Enable Password Retrieval
  2. Require Question and Answer
  3. Requires Unique Email
  4. Password Format
  5. Maximum Invalid Password Attempts
  6. Minimum Required Password Length
  7. Minimum Required Non-Alphanumeric Characters

While you could always modify the machine.config file, I do not recommend this course of action because in most cases no two applications will have the exact same requirements when it comes to Membership.

Customize the Web Forms

Take the Web forms you previously created and customize them to your needs. For the sake of brevity, I will cover the registration Web form; however, the others are included in the sample code. Since we are not going to require the user to enter a question and answer in the case of a forgotten password, we must modify our Web form (see Figure 7).

To accomplish this step, click the Customize Create User Step as shown in figure 10.

Figure 10: Customize Create User Step

Once you have performed this action, you can then remove the two rows that contain the labels, text fields, and required field validators. Save these changes, and at this point your Web form should look similar to Figure 11.

Figure 11: Customized Registration Web Form

Next, open the PasswordRecovery Web form and delete the QuestionTemplate section. At this point, your Web forms have been customized to meet the specifications of this article, but there are a few more steps you will need to accomplish in order to send the user his or her password via email.

MailDefinition Behavior of the PasswordRecovery Control

As I previously discussed about sending users their password, there are a couple of steps we must accomplish. First, we need to once again modify the web.config file to hold the necessary SMTP setting that we will be utilizing to send these types of emails.

Listing 4: SMTP Settings

<mailSettings>

  <smtp from="postmaster@anywhere.net">

    <network host="smtp.anywhwere.net" password="mypassword"

  userName="postmaster@anywhere.net" />

  </smtp>

</mailSettings>

Now the next step is to bring up the properties of the PasswordRecovery control and configure the appropriate settings.

Figure 12: MailDefinition Behavior

Once again, complete the necessary fields. One particular field I wish to draw your attention to is the BodyFileName. Here you can create a text file which will in turn contain the body of the email that will be sent to the user.

Listing 5: Example BodyFileName Text File

This is an automatically generated message. DO NOT REPLY TO THIS EMAIL.

You have created a new account at XYZ, and you may now log in.

Your username is:
UserName: <% UserName %>
Password: <% Password %>

To login, please visit:
http://www.xyz.net/Login.aspx?ReturnUrl=/Default.aspx

After logging in you may change you profile here:
http://www.xyz.net

Thanks,

Your Friendly Webmaster

For further details on the MailDefinition property, be sure to visit MSDN.

Put Everything Together

Now, we need to make a change to the web.config file concerning authentication.

Listing 6: Authentication Section

<authentication mode="Forms">

  <forms loginUrl="CustomFormAuthentication\Login.aspx"

  timeout="60"

  protection="All"

  slidingExpiration="true"/>

</authentication>

Create a new Web form and name it Default.aspx, performing the following actions:

  1. Drag and drop a LoginView control onto the form.
  2. Drag and drop a LoginStatus control into the LoginView Control.

Figure 12: Example Default.aspx Web Form

Now run your application and you will be presented the above screen in your browser. Click Login and ensure you can in fact successfully login to the application. If so, you should be returned to Default.aspx, and the LoginStatus control will now reflect your username along with an option to logout of the application.

Role Management

Apart from user authentication, most applications require some sort of role-based authorization. The role manager also uses some kind of provider to store the information related to roles and their mappings to users.

The machine.config file contains the default settings. To customize these setting all you need to do is modify your web.config.

Listing 7: Roles Configuration

<configuration>

  <connectionStrings>

    <add name="SqlServices" connectionString=

      "Data Source=servername;Initial Catalog=databasename;

       Integrated Security=SSPI;" />

  </connectionStrings>

 

  <system.web>

    <authentication mode="Forms" >

      <forms loginUrl="login.aspx"

      name=".ASPXFORMSAUTH" />

    </authentication>

 

    <roleManager defaultProvider="SqlProvider"

      enabled="true"

      cacheRolesInCookie="true"

      cookieName=".ASPROLES"

      cookieTimeout="30"

      cookiePath="/"

      cookieRequireSSL="false"

      cookieSlidingExpiration="true"

      cookieProtection="All" >

      <providers>

        <add

          name="SqlProvider"

          type="System.Web.Security.SqlRoleProvider"

          connectionStringName="SqlServices"

          applicationName="SampleApplication" />

      </providers>

    </roleManager>

  </system.web>

</configuration>

Some of the more important methods of the Roles class are as follows:

  1. CreateRole: Used to create a new role.
  2. GetAllRoles: Used to get all existing roles. It returns an array of strings.
  3. AddUserToRole: Adds a user to a role.
  4. RemoveUserFromRole: Removes a user from a role.
  5. IsUserInRole: Checks if a user belongs to a role.
  6. GetRolesForUser: Gets all roles for a particular user. It returns an array of strings.
Summary

As I have demonstrated, you can clearly see that implementing user authentication and roles within an application is not difficult at all thanks to .NET 2.0 and Visual Studio .NET 2005. The keys points to remember are as follows:

  1. Properly provision your database.
  2. Modify your web.config for custom authentication.
  3. Modify your web.config for custom role management

Microsoft has done an excellent job in this endeavor to assist both developers and businesses to do more faster and with greater productivity. Kudos Microsoft!



User Comments

No comments posted yet.

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-16 8:03:48 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search