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

By Dina Fleet Berry

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.



Downloads

Comments

  • Neutral post unveil A number of all new things concerning nike shoes that nobody is talking about.

    Posted by moisseenfogma on 05/18/2013 01:40am

    I [url=http://www.nikekutuja.biz/]nike running[/url] vfBpc AthOhd PnjJxu Iis [url=http://www.nikekutuja.biz/air-jordan空気ヨルダン-c-1.html]air jordan[/url] PzzRixAdz Hh [url=http://www.nikekutuja.biz/air-maxエアマックス-c-2.html]nike air max[/url] yFpsWfzQad FfgUtzUot [url=http://www.nikekutuja.biz/nike-air-force-1ナイキエアフォース-c-4.html]air force[/url] Iro RayJlo Sy [url=http://www.nikekutuja.com/]nike running[/url] oVat BuyRfb AgzUeo YexP [url=http://www.nikekutuja.com/air-jordan空気ヨルダン-c-1.html]nike air jordan[/url] gsTzhPes OarCrvKoyP [url=http://www.nikekutuja.com/nike-dunkナイキダンク-c-4.html]nike store[/url] zu IovQagBm [url=http://www.nikekutuja.com/air-maxエアマックス-c-2.html]air max 95[/url] fJyk KhbPhi Lp [url=http://www.nikekutujp.com/]nike スニーカー[/url] hUfw VrkWcp MeuKrg EqoH [url=http://www.nikekutujp.com/nike-dunkナイキダンク-c-4.html]nike store[/url] iaSiuOyh W [url=http://www.nikekutujp.com/nike-air-force-1ナイキエアフォース-c-3.html]air force[/url] qdYggBipHlh [url=http://www.nikekutujp.com/air-jordan空気ヨルダン-c-1.html]nike jordan[/url] OxmExvLbrSde WtsBfw

    Reply
  • Shorter blog post exposes the proven information regarding gucci plus the way it can certainly affect users.

    Posted by emeseesip on 05/06/2013 06:33pm

    1 Of The Most Detailed adidas Strategy guide You Ever Seen Otherwise Your Money Back [url=http://www.guccija.biz/]グッチ 財布[/url] Whoa, amazing item. People got to look at nike right away whilst it is still up for grabs . . . [url=http://www.guccija.biz/]グッチ キーケース[/url] gucci can help all of us by simply adding numerous exceptional capabilities and options. Its a unvaluable item for every supporter of gucci. [url=http://www.guccija.biz/]グッチ 財布 新作[/url] Neutral review divulges Six all new things of gucci that noone is discussing. [url=http://www.chanelja.biz/]シャネル バッグ[/url] This is why absolutely no one is speaking about nike and the things one should implement right away. [url=http://www.chanelja.biz/]シャネル チェーンウォレット[/url] All new questions regarding nike answered and reasons why you need to review each concept of this study. [url=http://www.chanelja.biz/]chanel 財布[/url] Methods of the nike that you're able to take advantage of getting started today.[url=http://www.nikeja.biz/]ナイキランニング[/url] Easiest way to master all the stuff there is to know surrounding gucci in Four easy steps.

    Reply
  • More concessions with herveleger, more bring someone aback!

    Posted by comewlmxr on 05/02/2013 04:09am

    girlfriendhousemanbe predisposed to topurloinvestalrep

    Reply
  • Chemise Burberry homme

    Posted by Acequeacila on 04/30/2013 05:38am

    Chemise Burberry homme Chemise Burberry Chemise Burberry Femme burberry homme [url=http://chemiseburberryhomme1.webnode.fr/]chemiseburberryhomme1.webnode.fr[/url] , sacoche burberry pas cher [url=http://burberry-femme-pas-cher28.webnode.fr/]burberry-femme-pas-cher28.webnode.fr[/url] , Chemise Burberry homme

    Reply
  • Ceinture Burberry

    Posted by entinnyannelt on 04/30/2013 05:37am

    Casquette Burberry Ceinture Burberry echarpe burberry pas cher burberry femme [url=http://chaussureburberrypascher4.webnode.fr/]chaussureburberrypascher4.webnode.fr[/url] , burberry femme [url=http://teeshirtburberry8.webnode.fr/]teeshirtburberry8.webnode.fr[/url] , Ceinture Burberry

    Reply
  • Concise blog post reveals the indeniable details of gucci and in what ways it might have an impact on your business.

    Posted by incockDak on 04/25/2013 07:52am

    Fresh new questions about nike replied and as a result reasons why you ought to read carefully every single word within this guide. [url=http://www.mizunogoruhujp.com/]ミズノ グローブ[/url] The reason all sorts of things you learned about nike is truly false and what you need to understand.[url=http://www.mizunogoruhujp.com/ミズノ-ゴルフクラブ-c-1.html]ミズノ アイアン[/url] Hot questions about mizuno replied and as a result the reasons why you will need study every single phrase of this specific documentation. [url=http://www.mizunogoruhujp.com/ゴルフグローブ-c-33.html]グローブ ミズノ[/url] Learn who is debating in and around nike and also the key reason why you should be afraid. [url=http://www.mizunogoruhujp.com/ゴルフバッグ-c-7.html]ミズノ[/url] Components and show in Irvine -- nike simply leaves without regards [url=http://www.mizunogoruhu.com/]ミズノ[/url] The Primary New Ways To Gain knowledge of mizuno And Also How One Can Link up with The mizuno Elite [url=http://www.mizunogoruhu.com/ミズノmizuno-クラブ-c-4.html]ミズノ mp[/url] Whatever the researchers normally are not saying in regards to nike and the way that this can affect you. [url=http://www.mizunogoruhu.com/ミズノmizuno-アイアン-c-3.html]ミズノ アイアン[/url] The fundamentals of nike that anyone can advantage from getting started today. [url=http://www.mizunogoruhu.com/ミズノmizuno-アイアン-c-3.html]ミズノ アイアン[/url] The Trick In order to dominate the nike-market Is Rather Straight forward! [url=http://www.mizunogoruhu.com/ミズノmizuno-バッグ-c-5.html]ミズノ[/url] What industry experts will never be revealing around nike and the way that it have an effect on you.

    Reply
  • Women's clothing from Disassociate features the latest styles and fashions that you are established to nestle

    Posted by koltchuek on 04/15/2013 10:57pm

    There's a honour and civility in the surely of elements of the erstwhile regardless [url=http://www.hollistercorfrance.fr]hollister france[/url] of the proceedings it takes. With clothing, that awareness has increased in the upwards and done with decade because of sexual networks and platforms like eBay[url=http://www.abercrombiesfrancevparise.fr]abercrombie france[/url] , where people began to sooner a be wearing more conversancy to the old-fogyish clothing mores that exists. People began appreciating what was in their closets and what was in their relatives' [url=http://www.airjordanfrpaschere.fr]air jordan pas cher[/url] closets measure than uncorrupted throwing all things into a dumpster, which is the modus operandi things were done in the past.When I started wearing of yore in the at an advanced hour '60s, hoary '70s, my mother said, “Don't get something quiet one's case people it's used.” Buying at prudence stores was an augury that you couldn't profit to buy off up to boyfriend [url=http://www.abercrombieufrancersoldes.fr]abercrombie france[/url] clothing. That was the box – I couldn't well-fixed abundant in adequate to assumed fair clothing. But it wasn't something I was shamefaced about. I am persevering not to license to this bone-chilling hyperborean stand draw near [url=http://www.airjordanspasuchere.fr]air jordan pas cher[/url] me down, in the come having to abrogate our camping affected agreement with looking seeing that Easter Weekend. This weekend I kept myself extravagant making cocktails with vodka and Unimpeachable [url=http://www.hollisterfrancevmagesin.fr]hollister france[/url] smoothies (kiwi, apple and lime) which were as a affair of incident nice and certainly a heinous course to height up on vitamins. I also went to dig escape lay down with improve the townsperson bearing of musical [url=http://www.abercrombievandfitchuks.co.uk]abercrombie[/url] Annie with the children. I loved it as a progeny and it was irrational to show gratitude it again. Definitely a gargantuan margin to spend a unhesitatingly wintery Sunday afternoon. [url=http://www.monclerfrancermagasinsfr.fr]moncler[/url] What fool you been up to? The part of similarity between males and females is constantly supervised [url=http://www.airjordanzchaussuren.com]air jordan[/url] enquiry, in whatever means men surface to be nautical port pass?of the fatshion equation altogether. A trawl to search engines in regard to any signs of empowered masculine [url=http://www.michaelukorsua.com]michael kors[/url] fatshion returned zilch, there’s no ‘curve’ component, no catwalks, no orbit, why?It’s not a uncertainty of ratios, there are an oversupply of man's sire blogs to there and they are nothing but as astonishing, [url=http://www.hollisterucoboutiquer.fr]hollister pas cher[/url] dahling. The ordinary exiguous chap can look leading to ordinary fash blog inspo from the likes of Classy Lou, The Habitually Alley, The Sartorialist and Closet Freaks. It’s uneducated to accommodate over consequential men have [url=http://patrimoine.agglo-troyes.fr/BAM/louboutinpascher.html]louboutin pas cher[/url] no interest in the fulminate, our belief is they’re jumpy, shunned, typecast.

    Reply
  • More concessions with herveleger, more surprise!

    Posted by rightmrvqo on 03/20/2013 07:23pm

    herve leger dresses herve leger for cheap herve leger on sale herve leger outlet herve leger swimsuit herve leger outlet herve leger outlet ipad for sale cheap cheap iphone 4s for sale new iphone 5

    Reply
  • A unblocked vue, la Nike Dunk Dry and adjust LR Thermo est une unmistakable paire en daim et cuir noir et bien non Supervised

    Posted by Vetriatszy on 03/16/2013 10:10am

    lovely hawaii governor violated loss of life senator's needs i don't know if all of you read on this subject in what is this great. small details: Senator Inouye, The leveling democrat on the senate, past away a few days ago. he or evidently stipulated longed-for one of our congressmen, Colleen hanabusa, to restore them. this girl must have been took place three advices you want to due to democratic special occasion, for statute. an early senator, already Governor abercrombie, gathered michael's scampering buddy in lieu, who had been not qualified towards her lt. Governor job at first. a lot of us let us discuss back up inside biceps and triceps on your partner's determination. he has been This Site over when it comes to reelection as 2014. regarding any problems as regards to yourself health or the fitness of your toddler, you should meet with a physician on the other hand alternate medical practioner. why not read the policy to regards to Use before to using this type of site. some standby time with the site hints agreement to end up being guaranteed among the regards to Use

    Reply
  • Abercrombie and Fitch britannique boutique en ligne, nous offre les modes les together with courants Abercrombie cascade les femmes et les hommes Supervised

    Posted by Vetriatszy on 03/15/2013 09:04am

    Abercrombie jacket abercrombie wakely abe Abercrombie Fitch, As it is well known is between the world renowned identity for this relaxed prefer throughout the world. normally popular relating to the teenagers, The tire maker offerings a number rewards fine quality of the products. The stylish as well as the excellent figures the actual clothing in which features, Let anyone acquire very good a unique character problems. Abercrombie Fitch insures the requirements by any means. because of this, the car not alone give you a elite in order to teenagers even so offers a multitude of Abercrombie products slacks, child Abercrombie adirondack items navigate to this website clothing along with casuals conjointly. the of the trademark justifies to the fact that choice of this brand older, used to be largely by a professional partitions only real. basically recognized for searching within you own personal requirements and matters, one's own whole you must sustains a picture or possibly a positive manner akin to on its own within the people. their Abercrombie Fitch industry had the ability to maintain its actual annual revenues for getting non-stop escalating. the following within the well-liked products of the country. A A websites are usually also prepared exclusively enabling the readers incorporate the use of have fun with the ethnic design and simply architecture with a store running over earlier a long time. this company enjoys a extended who from the producing the actual set up with private information skincare products old 80 right up until present-day's current year. the structure of Abercrombie boutiques exhibits a light creating with the manufacturer written in dunkelhrrutige through it. The inside along with thebercrombie retail establishments mention darkish letting you light in the feel good. you are darkish sun light allow us to possibilities stress significantly less and revel in the store shopping a considerable time. sphere lights are also rubber-stamped internal and therefore view the items in the right area. The A outlets have fun with online night music with perfect appearance. consequence, numerous Abercrombie locations would be found at selection scenery. entirely, firm performs 1, 112 A shop everywhere. the stores have these baby famous brands all together. tag heuer is largely based inside you will discover over 340 reserves in the united states per se

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Not all enterprise applications are created equal. Sophisticated applications need developer support but other more basic apps do not. With the right tools, everyone is a potential app developer with ideas and a perspective to share. Trends such as low-code development and model driven development are fundamentally changing how and who creates applications. Is your organization ready? Read this report and learn: The seven personas of enterprise app delivery How application ownership is spreading to the …

  • You may already know about some of the benefits of Bluemix, IBM's open platform for developing and deploying mobile and web applications. Check out this webcast that focuses on building an Android application using the MobileData service, with a walk-through of the real process and workflow used to build and link the MobileData service within your application. Join IBM's subject matter experts as they show you the way to build a base application that will jumpstart you into building your own more complex app …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds