asp tutorials, asp.net tutorials, sample code, and Microsoft news from 15Seconds
Data Access  |   Troubleshooting  |   Security  |   Performance  |   ADSI  |   Upload  |   Email  |   Control Building  |   Component Building  |   Forms  |   XML  |   Web Services  |   ASP.NET  |   .NET Features  |   .NET 2.0  |   App Development  |   App Architecture  |   IIS  |   Wireless
 
Pioneering Active Server
 Power Search








Active News
15 Seconds Weekly Newsletter
• Complete Coverage
• Site Updates
• Upcoming Features

More Free Newsletters
Reference
News
Articles
Archive
Writers
Code Samples
Components
Tools
FAQ
Feedback
Books
Links
DL Archives
Community
Messageboard
List Servers
Mailing List
WebHosts
Consultants
Tech Jobs
15 Seconds
Home
Site Map
Press
Legal
Privacy Policy
internet.commerce














internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

HardwareCentral
Compare products, prices, and stores at Hardware Central!

Writing a Custom Membership Provider for the Login Control in ASP.NET 2.0
By Dina Fleet Berry
Rating: 3.3 out of 5
Rate this article


  • email this article to a colleague
  • suggest an article

  • download source code
  • 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

    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.

    The Login Control and the Membership Provider

    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.

    Membership Providers

    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.

    Steps Involved when Using a Custom Provider with the Login Control

    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.

    How the Login Control Works

    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.

    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.

    Classes You Need to Provide

    • 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.

    MyCustomMembershipProvider : MembershipProvider

    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.

    Successful Validation with the Login Control

    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.

    Failed Validation with the Login Control

    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.

    Web.Config

    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>

    Required Config.Web Sections

    • 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.

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

    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.

    Summary

    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.

    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.

  • Rate This Article
    Not HelpfulMost Helpful
    1 2 3 4 5
    Other Articles
    Jul 21, 2005 - N-Tier Web Applications using ASP.NET 2.0 and SQL Server 2005 - Part 1
    While the .NET Framework made building ASP.NET applications easier then it had ever been in the past, .NET 2.0 builds on that foundation in order to take things to the next level. This article shows you to how to construct an N-Tier ASP.NET 2.0 Web application by leveraging the new features of ASP.NET 2.0 and SQL Server 2005.
    [Read This Article]  [Top]
    Apr 28, 2005 - New Files and Folders in ASP.NET 2.0
    With the release of ASP.NET 2.0, Microsoft has greatly increased the power of ASP.NET by introducing a suite of new features and functionalities. As part of this release, ASP.NET 2.0 also comes with a host of new special files and folders that are meant to be used to implement a specific functionality. This article examines these new files and folders in detail and provides examples that demonstrate how to utilize them to create ASP.NET 2.0 applications.
    [Read This Article]  [Top]
    Mar 10, 2005 - The DataSet Grows Up in ADO.NET 2.0 - Part 2, Cont'd
    Alex Homer continues his detailed look at the major changes to the DataSet class. In this part, he looks at two features that allow developers to work with data in a more structured and efficient way when using the DataSet with a SQL Server 2005 database server.
    [Read This Article]  [Top]
    Mar 9, 2005 - The DataSet Grows Up in ADO.NET 2.0 - Part 2
    Alex Homer continues his detailed look at the major changes to the DataSet class. In this part, he looks at two features that allow developers to work with data in a more structured and efficient way when using the DataSet with a SQL Server 2005 database server.
    [Read This Article]  [Top]
    Mar 3, 2005 - The DataSet Grows Up in ADO.NET 2.0 - Part 1, Cont'd
    In this article, Alex Homer looks at the changes between the version 1.x and version 2.0 DataSet and their associated classes, showing you how you can take advantage of the new features to improve your applications' capabilities and performance.
    [Read This Article]  [Top]
    Mar 2, 2005 - The DataSet Grows Up in ADO.NET 2.0 - Part 1
    In this article, Alex Homer looks at the changes between the version 1.x and version 2.0 DataSet and their associated classes, showing you how you can take advantage of the new features to improve your applications' capabilities and performance.
    [Read This Article]  [Top]
    Dec 29, 2004 - ClickOnce Deployment in .NET Framework 2.0
    In this article, Thiru Thangarathinam examines .NET 2.0's new ClickOnce deployment technology that is designed to ease deployment of Windows forms applications. This new technology not only provides an easy application installation mechanism, it also eases deployment of upgrades to existing applications.
    [Read This Article]  [Top]
    Dec 15, 2004 - A Sneak Peek at ASP.NET 2.0's Administrative Tools
    With ASP.NET 2.0, Microsoft has made great strides in increasing developer productivity and has made implementing previously complex solutions relatively easy. Where this version of ASP.NET really shines, however, is in its new administrative tools that allow developers to spend less time managing the configuration of the servers and software and more time developing great code.
    [Read This Article]  [Top]
    Nov 17, 2004 - The ASP.NET 2.0 TreeView Control
    Thiru Thangarathinam introduces ASP.NET 2.0's new TreeView control which provides a seamless way to consume and display information from hierarchical data sources. The article discusses this new control in depth and explains how to use this feature rich control in your ASP.NET applications.
    [Read This Article]  [Top]
    Oct 20, 2004 - Beyond the DataGrid: An Architectural View of the Data Source Model in ASP.NET 1.x and 2.0
    Dino Esposito discusses the differences between the DataGrid control in version 1.x and 2.0 of ASP.NET. In the process, he also builds an improved version of the 1.x control that can get you some of the new 2.0 features today.
    [Read This Article]  [Top]
    Mailing List
    Want to receive email when the next article is published? Just Click Here to sign up.

    Support the Active Server Industry



    JupiterOnlineMedia

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info


    Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

    Solutions
    Whitepapers and eBooks
    Microsoft Article: Will Hyper-V Make VMware This Decade's Netscape?
    Microsoft Article: 7.0, Microsoft's Lucky Version?
    Microsoft Article: Hyper-V--The Killer Feature in Windows Server 2008
    Avaya Article: How to Feed Data into the Avaya Event Processor
    Microsoft Article: Install What You Need with Windows Server 2008
    HP eBook: Putting the Green into IT
    Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
    Avaya Article: Setting Up a SIP A/S Development Environment
    IBM Article: How Cool Is Your Data Center?
    Microsoft Article: Managing Virtual Machines with Microsoft System Center
    HP eBook: Storage Networking , Part 1
    Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
    MORE WHITEPAPERS, EBOOKS, AND ARTICLES
    Webcasts
    Intel Video: Are Multi-core Processors Here to Stay?
    On-Demand Webcast: Five Virtualization Trends to Watch
    HP Video: Page Cost Calculator
    Intel Video: APIs for Parallel Programming
    HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
    Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
    MORE WEBCASTS, PODCASTS, AND VIDEOS
    Downloads and eKits
    Sun Download: Solaris 8 Migration Assistant
    Sybase Download: SQL Anywhere Developer Edition
    Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
    Red Gate Download: SQL Compare Pro 6
    Iron Speed Designer Application Generator
    MORE DOWNLOADS, EKITS, AND FREE TRIALS
    Tutorials and Demos
    How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
    eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
    IBM Article: Collaborating in the High-Performance Workplace
    HP Demo: StorageWorks EVA4400
    Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
    Microsoft How-to Article: Get Going with Silverlight and Windows Live
    MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES