Wednesday 13 October 2010

Developing a custom MembershipProvider

there are some samples out there on the net just showing what the default providers already do: Using an SQL DB as the source. They even concentrate on the SQL stuff, instead on the MembershipProvider implementation.

So here we go, a very simple example:

First create a new class that inherits from the abstract MembershipProvider class.

public class MyMembershipProvider : 
System.Web.Security.MembershipProvider

We just need to implement two simple methods and one property to get started:

public override void Initialize(string name, 
System.Collections.Specialized.
NameValueCollection
config)
{
//base.Initialize(name, config);
//read you config settings and
        //do whatever you need here
}



If you connect to some database init your db settings here, or read your web service settings if you plan to consume a web service later.


Next, we implement the ValidateUser method:


public override bool ValidateUser(string username, 
string
password)
{
if (username == "user" && password == "pass") return true
;
return false
;
}


This is just a sample to let you see how it works, of course you are going to implement here the validation to you backend, be it LDAP, a DB, web services or whatever.


The last thing is the property Name. As long as I did not implement this the login failed, throwing an exception.


    public override string Name
    {
       
get
        {
           
return "SampleMembershipProvider";
        }
    }


Basically this is the name you refer to in the configuration.


Now on to the web.config. We add the MembershipProvider and declare that /images may be accessed by everyone (*), but /locked only by authenticated users. And we need to configure the authentication:


<authentication mode="Forms">
   <
forms name=".ASPXAUTH"
loginUrl="~/Default.aspx"
protection="Validation"
timeout="999999"
    />
</
authentication>



<membership defaultProvider="SampleMembershipProvider" 
userIsOnlineTimeWindow="15"
>
<
providers
>
   <
add name="SampleMembershipProvider"
type="MyMembershipProvider"
/>
  </
providers
>
</
membership
>
</
system.web
>
<
location path="images"
>
  <
system.web
>
     <
compilation debug="true"
/>
      <
authorization
>
         <
allow users="*"
/>
       </
authorization
>
     </
system.web
>
  </
location
>
  <
location path="locked"
>
    <
system.web
>
      <
compilation debug="true"
/>
      <
authorization
>
        <
deny users="?"
/>
      </
authorization
>
    </
system.web
>
  </
location>



Now we place the asp:Login control on our default.aspx page (we told web.config that this is the login page).


<asp:Login RememberMeSet="True" runat="server"
 ID="logincontrol"
MembershipProvider="SampleMembershipProvider"
DestinationPageUrl="~/locked/securedpage.aspx">
</asp:Login>


Thats it. Have fun.