ASp.net 2.0 step by step Membership Provider

Hi,

 this is Satalaj here I will configure ASP.net web application to use Membership providers.

After reading this article. You will be able to perform following tasks. To speed up the performance of membership provider
don't forget to read Omar Al Zabir's post here http://omaralzabir.com/optimize_asp_net_membership_stored_procedures_for_greater_speed_and_scalability/
it will help you to look work on Sql hints like nolock, readpast etc. and you will succesfully resolve the issues regarding tablelocks or transaction dead locks.

1. Setup Asp.net Membership provider Data base using MS SQL server 2005.
2. Create user
3. Create Role Add user in Role
4. Provider Role base security to your application.
5. Redirecting authorized users to see his web section to which he is authorized to see
6. Password recovery control and configuration.
7. Single Sign in / single login / single signin  
8. For Single sign on using asp.net  follow this link on code projects and 4 guys from rolla

For NLB network load balancing refer west-wind



1.  Open ASPnet_RegSQL.exe and Run 

$:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regsql.exe 

Note** $ is your root driver where windows is installed

Alternatively you can open .net command prompt and run aspnet_regSQL

1.1 Opened wizard will guide you through the rest of setup. 
      Select your DB where you would like to install 
       wizard tool will generate ASP.net membership provider Tables ,views and stpred procedures automatically in your DB.

2. Create new Asp.net web site using C# language as a code behind
   
   
Add Web.Config file your web application it will look like this as shown below

   

 <?xml version="1.0"?>
     
<configuration>   
      
<
appSettings
/>
      
    <connectionStrings/>
   
           
<
system.web>    
       
             
<
compilation debug="false" />      
       
             
<
authentication mode="Windows" />       
   
           
</
system.web
>
    
</configuration
>

   

2. Configure Membership provider in web.config
    First we will add connection string to the Database where we have created ASpnet Database  and tell   
    the provider to use that using connectionStringName.  

       <connectionStrings>  
            
<
add name=
"aspnetdbConnectionString" 
                  
connectionString="Data Source=;Initial Catalog=;Persist Security Info=True;User ID=;Password="
                 
providerName="System.Data.SqlClient" />
        
</connectionStrings>  

       
 
2.1 Use Forms authentication

  
        <authentication mode="Forms" >                                    
       
</
authentication> 
  

2.2 Set Forms authentication Cookie namd , Redirect to Login path and Default path
 
    <compilation debug="false" />
 
     <authentication mode="Forms" >                 
         
<
forms defaultUrl=
"default.aspx"
                
name="myform"

                
timeout="5"

                
loginUrl="~/login.aspx"

                
slidingExpiration="true"
>
          </
forms>
          
      
</
authentication>

     

2.3
    Add Membership tag in web.config.
    Take a closer look at bold words
     <membership defaultProvider="xyzMembershipProvider">       
       
<
providers
>
       
 <clear/>
 
         
<
add name=
"xyzMembershipProvider"
             
type="System.Web.Security.SqlMembershipProvider"
 
              
applicationName="/myApp"

             
connectionStringName="aspnetdbConnectionString"/>
       
         
</
providers>
   
    
</
membership
>

     
  
Don;t forget to add applicationName attribute in your membershipprovider otherwise it will generate GUID in aspnet_Applications table


Note**: Now your web application is ready to use Bult in login Controls 
Drag and drop
1.Create user Wizard
2. Login status 
3. Login control to see how it works.


Now we will programmatically create the user and  Roles. we will add user in to role.

Here is code snippet. It will help you while migrating your exsting user management system to ASP.net provider based membership management

   protected void Button1_Click(object sender, EventArgs e)   
  
{        
        
     
MembershipCreateStatus status;
        
   
MembershipUser user = Membership.CreateUser("Satalaj","P@ssw0rd","satalajmore-aspnet@yahoo.co.in","Who am I ?","Satalaj",true,out status);
   
switch(status)
        
      
{
           
                
case MembershipCreateStatus.DuplicateUserName:
               
                
Response.Write("User already exists in system. please select diffrent name and try again");
                 
break;
           
                
case MembershipCreateStatus.DuplicateEmail :
           
                
Response.Write("Duplicate Email");
           
                
break;
           
                
case MembershipCreateStatus.Success :
            
                
Response.Write("User has been created successfuly");
               
                
break;
 
        
        
}
 
   
   }
  



3.    Create Role if Role dosen;t exists in to the system

protected void Button2_Click(object sender, EventArgs e)    
 
{
       
   
if(!Roles.RoleExists("Editor"))
        
    {
          
      
Roles.CreateRole("Editor");
        
        
}
   
    
}
 

 

      
3.1 Add user into Editor Role if he Is not in that role.
  

protected void Button3_Click(object sender, EventArgs e)   
   {    
    
if(!Roles.IsUserInRole("satalaj","Editor"))
         
            {
 
              
Roles.AddUserToRole("satalaj","Editor");
        
            
}
    
 
}
  

  

4.  How to prevent anonymous users from accessing Folder contents of Editor.

        Now we will add New folder called editor and we will authorize only users who are in Editor role to view the contents of that folder 

       To do that Add below web.config file into editor folder

       Note** Whatever you pot inside this Editor folder that will be available to only loged in users 
   
                   to do that we added web.config file in it as shown below.

<?xml version="1.0"?> 
    
<configuration>
    <appSettings
/>
    <connectionStrings
/>
      <system.web
>
            <authorization
>
                  <deny users=
"?"/>
                  <allow roles="Editor"/>
 
          </authorization>
      </system.web
>
  
</configuration> 


5. Login user and redirect logged in user to his authorized section based on his roles

protected void Button4_Click(object sender, EventArgs e)
  {
        if(Membership.ValidateUser("satalaj",P@ssw0rd))
    {
      FormsAuthentication.SetAuthCookie("satalaj",true);
  
 
       if(Roles.IsUserInRole("satalaj","Editor"))
            
               
{
               
                     
Response.Redirect("~/Editor/manageArticles.aspx");
            
        
}
 
        
        
}
    
 
}

 

      Put some .pdf file init say sat.pdf is located in Editor and try to access in browser


http://yourapplication/Editor/sat.pdf

if you are authonticated and your role is Editor then  you will be able to access this sat.pdf

Now clear cookes and try to authonticate without login
you will be redirected to login page.

Next we will see hot to configure password recovery control. and email configuration.


To Configure your Password recovery control add below tag in your web.config.

<system.net>
 <
mailSettings
>
  <
smtp from="satalaj@sat.com"
>
      <
network host="smtp.server.address.com" port="25" userName="mysmtpUserName@smtp.com" password="password"
/>
   </
smtp
>
</
mailSettings
>
</
system.net
>

 
Drag and drop Pasword recovery control into your web.config

If you want to configure smtp.gmail.com with password recovery control then follow steps given
by me here
http://forums.asp.net/t/1250771.aspx?PageIndex=1

After configuring your email settings take a look at web.config it should look like below one

<?xml version="1.0"?>
    <
configuration
>
       <
appSettings
/>
       <
connectionStrings
>
       <
add name="aspnetdbConnectionString"

              
connectionString="Data Source=;Initial Catalog=;Persist Security Info=True;User ID=;Password="

              
providerName="System.Data.SqlClient"
/>
       </
connectionStrings>
   <system.web>
      <
compilation debug="true"
/>
      <
authentication mode="Forms"
>
      </
authentication
>
   <
membership defaultProvider="xyzMembershipProvider"
>
   <
providers
>
    <
clear
/>
    <
add name="xyzMembershipProvider
"
          
 type="System.Web.Security.SqlMembershipProvider"

          
applicationName="/myApp"
 
           
connectionStringName="aspnetdbConnectionString"
/>
    </
providers
>
  </
membership
>
<
roleManager enabled="true" defaultProvider="xxxRoleManagerProvider">
  <
providers
>
   <
add name="xxxRoleManagerProvider"

         
type="System.Web.Security.SqlRoleProvider"

         
applicationName="/myApp"

         
connectionStringName="aspnetdbConnectionString"
/>
  </
providers
>
</
roleManager
>
</
system.web>
<system.net>
   <
mailSettings
>
   <
smtp from="satalaj@sat.com"
>
    <
network host="smtp.server.address.com" port="25" userName="mysmtpUserName@smtp.com" password="password"
/> 
    </
smtp
>
   </
mailSettings
>
</
system.net
>

</
configuration>


For more information about the tags and code visit
http://msdn.microsoft.com/en-us/library/ms998347.aspx

7. Single sign in
  
    If you want two users not to sign in using same creadentials then it can be avoided using below code 
    
 
MembershipUser user = Membership.GetUser(login1.UserName);

      if (user.IsOnline)

   {

      //cancel login...redirect to not allowed page

   }


   
   In web.config membership tag add attribute userIsOnlineTimeWindow= 1 . 

If the LastActivityDate for a user is greater than the current date and time minus the UserIsOnlineTimeWindow value in minutes, then the user is considered online.

e.g.

<membership defaultProvider="SqlProvider"   userIsOnlineTimeWindow="1">
  <providers>
    <add name="SqlProvider"
      type="System.Web.Security.SqlMembershipProvider"
      connectionStringName="SqlServices"
      enablePasswordRetrieval="true"
      enablePasswordReset="false"
      requiresQuestionAndAnswer="true"
      passwordFormat="Encrypted"
      applicationName="MyApplication" />
  </providers>
</membership>

http://msdn.microsoft.com/en-us/library/system.web.security.membership.userisonlinetimewindow.aspx


For more information about the tags and attributes  visit

http://msdn.microsoft.com/en-us/library/ms998347.aspx .

 Satalaj

Author

My name is Satalaj, but people call me Sat. Here is my homepage: . I live in Pune, PN and work as a Software Engineer. I'm former MVP in ASP.net year 2010.
Disclaimer: Views or opinion expressed here are my personal research and it has nothing to do with my employer. You are free to use the code, ideas/hints in your projects. However, you should not copy and paste my original content to other web sites. Feel free to copy or extend the code.
If you want to fight with me, this website is not for you.
 

I'm Satalaj.