Writing a Custom Membership Provider for the Login Control in ASP.NET 2.0

In ASP.NET 2.0 with Visual Studio (VS) 2005, you can program custom authenticated pages quickly with the Membership Login controls provided. These controls can be found in VS 2005 in the toolbox under the Login section and include: Pointer, Login, LoginView, PasswordRecovery, LoginStatus, LoginName, CreateUserWizard, and ChangePassword. These controls can be found in the framework library as a part of the System.Web.Security namespace. This article will focus on the Login control.

Note: This article was written based on the November 2004 Community Release version of Visual Studio 2005. Due to the pre-release status of the information in this article, any URLs, Class names, Control names, etc may change before release.

What This Article Covers

The Login Control and the Membership Provider

Membership Providers

Steps Involved when Using a Custom Provider with the Login Control

How the Login Control Works

Classes You Need to Provide

MyCustomMembershipProvider : MembershipProvider

Successful Validation with the Login Control

Failed Validation with the Login Control

Web.Config

Required Config.Web Sections

Why Use the New ASP.NET 2.0 Membership Controls at All?

Summary

References

 

The current MSDN location for the documentation is:
http://whidbey.msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_fxnetstart/html/50c4d770-0bb4-4e6a-bcf0-966bc7a3de77.asp.

System.Web.Security:
http://whidbey.msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/N_System_Web_Security.asp.

System.Web.UI.WebControls:
http://whidbey.msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/T_System_Web_UI_WebControls_Login.asp.

The new Login control provided with ASP.NET 2.0 is a simple way to implement validation for your web site. Developing a custom provider to interact with your own membership database is easy.

Since there is some programming work to get the new controls to talk to your old database structure, you may be asking yourself is it worth the trouble? The answer to this seems to be an active debate on several discussion boards.

The benefits of this method are:

  1. You can program the custom provider to provide as little or as much as you need. If you just want the Login control to work with your custom membership database, you don't necessarily have to write a lot of code. You will have to be more thoughtful in your upfront design to make sure you are covering just what you need.
  2. The new web-based Membership Administration functionality in ASP.NET 2.0 will consume your custom provider. So you get both the ability to use the new controls and the ability to use the new web-based administration features.
  3. Assuming Microsoft will grow this area of functionality overtime, you can continue to make use of your original work.

The disadvantages of this method are:

  1. The new login controls may be more, less, or different than what you need for your web site. Most web sites already have this membership authentication functionality so rewriting just to get it into ASP.NET 2.0 is probably a poor decision.
  2. If you have your own administration web site or program for your custom membership, writing the additional code to make use of the new web-based Membership Administration functionality is not necessary -- just don't write those pieces. It's easy to tell which pieces to skip because all the required functions for the web-based administration deal with collections of users whereas the Login control functions deal with a single user.
  3. Microsoft may abandon these controls. It's not likely but it is possible.

  • Authorization: This section specifies who can access that location (directory).
  • Authentication: This section specifies how the location is accessed. In the above example the <authentication> section is specified for the entire web site and uses the ~/support/login.aspx file as the authentication file. This is the file where the Login control will be used.
  • Membership: This is the section that ties the Login control to the custom membership provider.

The web.config file will need several new pieces. In order to glue the Login control to your custom membership provider, you will need a section called <membership>. You can set the properties of the custom provider in this section. You can also control these properties from the custom membership provider class. The web.config used for this article assumes some aspx files should be accessible only after login is validated, and some files should always be available. The two types of files are located in the 'support' and 'support_unrestricted' directories used in the <location> tags.

<?xml version="1.0"?>
<configuration >
  <appSettings>
    <add key="ConnectionString" value="server=XXX;database=XXX;uid=XXX;password=XXX;"/>
  </appSettings>
  <system.web>
    <compilation debug="true"/>
    <authorization>
      <allow users="*" />
    </authorization>
    <authentication mode="Forms">
      <forms name=".ASPXAUTH"
        loginUrl="~/support/Login.aspx"
        protection="Validation"
        timeout="999999"
      />
    </authentication>
    <membership defaultProvider="MyCustomMembershipProvider" userIsOnlineTimeWindow="15">
      <providers>
        <add name="MyCustomMembershipProvider"
          type="PostPointSoftware.MyCustomMembershipProvider"
          enablePasswordRetrieval="true"
          enablePasswordReset="true"
          requiresQuestionAndAnswer="false"
          applicationName="/"
          requiresUniqueEmail="true"
          passwordFormat="Clear"
          description="Stores and retrieves membership data from SQL Server"
          decryptionKey="68d288624f967bce6d93957b5341f931f73d25fef798ba75"
          validationKey="65a31e547b659a6e35fdc029de3acce43f8914cb1b2
                         4fff3e1aef13be438505b3f5becb5702d15bc7b98cd
                         6fd2b7702b46ff63fdc9ea8979f6508c82638b129a"
        />
      </providers>
    </membership>
  </system.web>
  <location path="images">
    <system.web>
      <compilation debug="true"/>
      <authorization>
        <allow users="*" />
      </authorization>
    </system.web>
  </location>
  <location path="support">
    <system.web>
      <compilation debug="true"/>
      <authorization>
        <deny users="?" />
      </authorization>
    </system.web>
  </location>
  <location path="support_unrestricted">
    <system.web>
      <compilation debug="true"/>
      <authorization>
        <allow users="*" />
      </authorization>
    </system.web>
  </location>
</configuration>

The login control has many properties, methods, and events to manage the look and feel of the control both on the first instance of the page as well as post back. A default failure message is provided and will appear on the Login control if validation is unsuccessful.

Upon successful validation, the Login control will redirect to the page referenced in the DestinationPageURL property, let's call this page hello.aspx. This valid user is now in a context variable and can be retrieved with the Context.User.Identity property.

This class is called from the login control for validation of the user's email and user's password. This class has several properties and methods that are required to make the glue between the Login control and your custom provider due the the inheritance from MembershipProvider. You will see in MyCustomMembershipProvider that they are provided but throw "not implemented" exceptions.

The two important methods in MyCustomMembershipProvider for the the custom provider are Initialize, and ValidateUser. Initialize is another place besides the web.config file to set properties for your custom provider. ValidateUser is the main function for the Login control to validate the user and password.

public override bool ValidateUser(string strName, string strPassword)
{
    //This is the custom function you need to write. It can do anything you want.
    //The code below is just one example.

    // strName is really an email address in this implementation

    bool boolReturn = false;

    // Here is your custom user object connecting to your custom membership database
    MyUserProvider oUserProvider = new MyUserProvider();
    MyUser oUser = oUserProvider.FindUser(strName);

    if (oUser == null)
        return boolReturn;

    // Here is your custom validation of the user and password
    boolReturn = oUser.ValidateUsersPasswordForLogon(strPassword);

    return boolReturn;
}

ValidateUser takes two parameters which are the Name and Password of the user. For many web sites, the Name will be the User's email address. The method returns true or false depending on the results of this validation. All the code inside the method is up to you to provide. The code provided in this above example is just one possibility.

  • A custom class inheriting from System.Web.Security.MembershipProvider. In this article, it will be called MyCustomMembershipProvider. This is the custom membership provider.
  • A class or classes that glue the above custom class to your database. In this article, these will be called MyCustomUser and MyCustomUserProvider. These two classes could have easily been combined into a single class. This is a choice you can make as you write your own provider implementation. Note: If you were implementing the standard providers in the framework provided for Active Directory or SQL Server, you would use the MembershipUser class from the framework for this.

The Login control provides two textboxes for a User Email and a User Password, along with a submit button. Once the user provides this information and clicks on the submit button, the custom membership provider class is called to authenticate the user. Once the user has been authenticated, the Context.User.Identity.IsAuthenticated property is set to true. The login control's DestinationPageURL property tells the web site where to direct the user if the validation is successful.

Writing a Custom Membership Provider for the Login Control in ASP.NET 2.0

The Login control is found in the Framework as a part of the System.Web.UI.WebControls namespace as the Login class. This class contains the functionality for the Login control. The majority of the functionality deals with visual style and event handling.

<asp:Login ID="Login1" runat="server" DestinationPageURL="support.aspx" ></asp:Login>

You don't need to have any code in the Login.aspx.cs code page. The control knows how to call the custom provider which does all the work because the provider is listed in the web.config. If you wanted to change the look and feel of the control on first time to the page or post back, you could manipulate the properties, methods, and events in the code behind. But again, that is optional.

For this article, the login.aspx.cs code behind page is a shell page provided by Visual Studio with no changes.

There are three main steps required to use a custom provider with the Login control.

  • The login control needs to be placed on a aspx page (login.aspx).
  • The custom provider class needs to inherit from MembershipProvider and override certain methods.
  • The web.config file needs to be modified to use a custom provider.

The Login controls ship with at least two Microsoft-supplied providers: Active Directory and SQL Server. Both of these providers use a specific data schema. This is great for new web sites, where an authentication schema is not already established, because you can adopt one of these types of authentication and have the majority of the design and programming work done for you. However, if you are working with an existing database structure, you can easily program a custom provider to get these new Login controls to talk to your old data structure.

A membership provider is the glue between the Login control and the membership database. The login control doesn't care if the membership provider is a custom provider or a Microsoft provider. The login control knows which provider to instantiate based on entries in the web.config file. The custom provider acts just like the Microsoft-supplied providers because it inherits from and overrides the MembershipProvider class.

This article focuses on the Login control using a custom SQL server membership database. None of the other controls will be discussed and none of the functions for the web-based membership administration will be covered. For functionality and brevity, this article provides the minimum required to connect the Login control with the custom membership provider. You should explore both the control and the MembershipProvider class in the framework to explore your options.

你可能感兴趣的:(Provider)