Plugging in your own Membership provider

Somebody who followed an ASP.NET course with me couldn’t find the necessary plugs to add your own providers to the .NET infrastructure. Since more will probably benefit I’m sharing with you all the necessary steps.

So you have your users stored somewhere in a database and can’t use the out of the box implementations that ship with the .NET framework. What are the steps that you need to do?

First, create a class that inherits from the abstract MembershipProvider and implement all the functionality you want to support. The more you add the better all the components that rely on it will be able to function. To just get beyond an MVC3 login page or a login with an ASP.NET webcontrol you just need to implement the validate user method.

//other methods omitted for brevity
public override bool ValidateUser(string username, string password)
    //here you'll connect with your custom database or service
    using (var context = new MyUserContext())
        var user = context.MyUsers.Where(x => x.Name.Equals(username)).SingleOrDefault();
        return user != null;

For this demonstration I’m just checking if I have a user with the same username in my database.

With our class in place we now need to plug it into the provider model, open your web.config navigate to the system.web node and configure your provider. If you added any additional configuration properties in your custom provider you can configure them there as well.

<membership defaultProvider="MyMembershipProvider">
        <add name="MyMembershipProvider" 
             applicationName="/" />


More guidance can be found on MSDN.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.