Home
Products
Forums
Help
Publish Article
Go Freelance

Write custom membership provider for ASP.Net

Downloads

If you are seeing this section and do not see download links, this means that you are not logged into our site. If you already are a member, click on the login link and login into site and come back to this page for downloading the control files. If you are not a member, click on registration link to become a Winista member and download the control for free.

If you are migrating from ASP.Net 1.1 to ASP.Net you probably have invested lot of time and effort in developing DAL to validate user and other user authentication and authorization related code. And now you want to make use of the new Role, Membership and Profile infrastructure introduced in ASP.Net 2.0. I am sure that you would want to use the same DAL implementation and plug it into the new architecture. So one of the steps towards would be to provide a custom Membership provider and plug that in. This article will describe some basic information about that. Following are the steps that you would need to take to create a custom provider.

  1. Create new class and derive from MembershipProvider

  2. Add System.Web.Security namespace for MembershipProvider otherwise you will get compile time error

    "The type or namespace name 'MembershipProvider' could not be found (are you missing a using directive or an assembly reference?)
  3. Add reference to System.Web assembly otherwise you will get error

    "The type or namespace name 'MembershipProvider' does not exist (are you missing an assembly reference?)"
  4. Add reference to System.Configuration assembly otherwise you may get compile time error

    "The type 'System.Configuration.Provider.ProviderBase' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Configuration"
  5. Now if you compile without adding any implementation to this class, you will get whole bunch of error complaining about certain methods or properties not being implemented. This means that base class MembershipProvider has defined whole bunch of methods and properties with attribute "abstract" or "Must Override" and all derived classes will have to implement them. Here is complete list of errors that you may get if no implementation is added to the class.

    error CS0534: does not implement inherited abstract member 
        'System.Web.Security.MembershipProvider.EnablePasswordRetrieval'
    error CS0534: does not implement inherited abstract member 
        'System.Web.Security.MembershipProvider.EnablePasswordReset'
    error CS0534: does not implement inherited abstract member 
        'System.Web.Security.MembershipProvider.RequiresQuestionAndAnswer'
    error CS0534: does not implement inherited abstract member 
        'System.Web.Security.MembershipProvider.ApplicationName'
    error CS0534: does not implement inherited abstract member 
        'System.Web.Security.MembershipProvider.ApplicationName'
    error CS0534: does not implement inherited abstract member 
        'System.Web.Security.MembershipProvider.MaxInvalidPasswordAttempts'
    error CS0534: does not implement inherited abstract member 
        'System.Web.Security.MembershipProvider.PasswordAttemptWindow'
    error CS0534: does not implement inherited abstract member 
        'System.Web.Security.MembershipProvider.RequiresUniqueEmail'
    error CS0534: does not implement inherited abstract member 
        'System.Web.Security.MembershipProvider.PasswordFormat'
    error CS0534: does not implement inherited abstract member 
        'System.Web.Security.MembershipProvider.MinRequiredPasswordLength'
    error CS0534: does not implement inherited abstract member 
        'System.Web.Security.MembershipProvider.MinRequiredNonAlphanumericCharacters'
    error CS0534: does not implement inherited abstract member 
        'System.Web.Security.MembershipProvider.PasswordStrengthRegularExpression'
    error CS0534: does not implement inherited abstract member 
        'System.Web.Security.MembershipProvider.CreateUser'
    error CS0534: does not implement inherited abstract member 
        'System.Web.Security.MembershipProvider.ChangePasswordQuestionAndAnswer'
    error CS0534: does not implement inherited abstract member 
        'System.Web.Security.MembershipProvider.GetPassword'
    error CS0534: does not implement inherited abstract member 
        'System.Web.Security.MembershipProvider.ChangePassword'
    error CS0534: does not implement inherited abstract member 
        'System.Web.Security.MembershipProvider.ResetPassword'
    error CS0534: does not implement inherited abstract member 
        'System.Web.Security.MembershipProvider.UpdateUser'
    error CS0534: does not implement inherited abstract member 
        'System.Web.Security.MembershipProvider.ValidateUser'
    error CS0534: does not implement inherited abstract member 
        'System.Web.Security.MembershipProvider.UnlockUser'
    error CS0534: does not implement inherited abstract member 
        'System.Web.Security.MembershipProvider.GetUser'
    error CS0534: does not implement inherited abstract member 
        'System.Web.Security.MembershipProvider.GetUser'
    error CS0534: does not implement inherited abstract member 
        'System.Web.Security.MembershipProvider.GetUserNameByEmail'
    error CS0534: does not implement inherited abstract member 
        'System.Web.Security.MembershipProvider.DeleteUser'
    error CS0534: does not implement inherited abstract member 
        'System.Web.Security.MembershipProvider.GetAllUsers'
    error CS0534: does not implement inherited abstract member 
        'System.Web.Security.MembershipProvider.GetNumberOfUsersOnline'
    error CS0534: does not implement inherited abstract member 
        'System.Web.Security.MembershipProvider.FindUsersByName'
    error CS0534: does not implement inherited abstract member 
        'System.Web.Security.MembershipProvider.FindUsersByEmail'
    							        

Now I will discuss each of these properties and methods and add implementation of these in our custom membership class.

ApplicationName

This property associates a user account with a particular application. This property will make more sense if you are planning to use same database for different application and user is going to different membership and profiles for each application. But if you are leveraging existing database which does not care about the application name to user association, then you can put empty implementation in your class. For example following code snippet show what an empty implementation may look like.

public override string ApplicationName
{
  get{return String.Empty;}
  set{;}
}							    
							    

And similarly you can deal with other properties for which you really do not have any values or fields in the existing database tables. The following methods are the ones that you really need to pay attention to and implement to leverage existing authentication and authorization infrastructure.

ValidateUser

This is the first most important method you will have to implement in custom MembershipProvider. This is where you will put your authentication code to verify if user provided correct credentials for logging into the application or not. Two parameters to this method are user login and user password. These parameters will be filled in by framework for you. You method need to return a boolean value indicating if the credentials are valid or not. So if you already have a method that verifies credentials for you, then only thing that you need to do is simply call that method from with in this method and return appropriate true or false value. For example in the demo project I have an existing class UserLogin which I used to use to validate user credentials. Now I want to leverage the same implementation but use custom Membership provider to validate user login. My implementation for ValidateUser looks like following code snippet.

public override bool ValidateUser(string username, string password)
{
    return UserLogin.VerifyUserLogin(username, password, m_strConnectionString);
}							    
							    

Similarly you can implement other methods like GetUser, FindUserByName, FindUserByEmail depending on what your existing DAL has implementation in place for.

How to deploy membership provider

Configuring your ASP.Net application to use your custom implementation of membership is as simple as adding some configuration entries in your web.config file. Following snippet shows what new entries you need to add to configure your application to start using your custom Membership provider class.

<configuration>							    
    <connectionStrings>
		<add name="MySqlConnection" 
		    connectionString="Data Source=localhost;Initial Catalog=netomatix;user id=sa;password=;" />
	</connectionStrings>							    
    <system.web>							    
	    <membership defaultProvider="MyCustomProvider" userIsOnlineTimeWindow="15">
		    <providers>
			    <clear />
			    <add 
			      name="MyCustomProvider" 
			      type="Winista.DemoData.MyMembershipProvider" 
			      connectionStringName="MySqlConnection"
			      applicationName="RoleMembershipDemo"
			      enablePasswordRetrieval="false"
			      enablePasswordReset="true"
			      requiresQuestionAndAnswer="false"
			      requiresUniqueEmail="true"
			      passwordFormat="Hashed" />
		    </providers>
	    </membership>
    </system.web>		
</configuration>
							    

Notice that we have specified name MyCustomProvider for our membership provider and the same name has been used in defaultProvider attribute of membership tag. Important thing is that you need to specify correct value of type attribute in provider settings. This type is the Type or fully qualified name of the class of your custom membership provider class. For example in demo project the provider has been implemented in MyMembershipProvider under Winista.Demo namespace, so I have supplied full name of the type in type attribute. If you fail to specify correct name then your provider will not get called. Other values for attributes are very self explanatory.

Connecting Custom Membership Provider With Login Control

You need to put a asp:login control on your page and specify membershipprovider property to name of the provider that we have setup in web.config file.

<asp:login id="ctlLogin" runat="server" 
    onauthenticate="OnAuthenticate" onloggedin="OnLoggedIn" 
    onloggingin="OnLoggingIn" destinationpageurl="~" 
    membershipprovider="MyCustomProvider" />
							    

And in the event handler OnAuthenticate which gets called when OnAuthenticate event fires you will be calling ValidateUser method.

protected void OnAuthenticate(object sender, AuthenticateEventArgs e)
{
    if (Membership.ValidateUser("foo", "bar"))
    {
        e.Authenticated = true;
    }
}							    
							    

In this article I have described basic implementation and usage of custom membership provider. In future articles I will provider more advanced implementation and usage.

Go Freelance
Home     About us     Contact us    Copyright    Privacy Policy    Return Policy    Advertisers
Copyright © Netomatix