Wednesday, November 9, 2011

Asp.Net Membership and Role Provider

Introduction

Asp.Net 2.0 provides built in controls to manage Membership in Web Applications. All these controls use Asp.Net providers that are loaded via web.config file. Membership provider and Role provider allows a complete system to maintain users information, authenticate and authorize the users. This article demonstrates how to use and configure the default Member ship and Role provider.

Implementing the Membership and Role provider:

Initially by using the visual studio 2005/2008/2010, create an Asp.Net website/web application. If u r using Visual studio 2010. Login and Registration pages are available by default in the application. Create Registration page and then drag the Create User Wizard control from the Login controls section of the Toolbox. Now to store the user information we need to create the database in the SQL Server. Follow the following steps to use built in user store schema for maintaining the user information.
  1. Go to Visual Studio, Visual Studio tools and then open the Visual Studio Command Prompt.
  2. Use the aspnet_regsql.exe command to run the ASP.NET SQL Server Setup Wizard.
  3. Check the option “Configure SQL Server for application services”.
  4. Select the Server Instance and the database name for the application, if the database name is not provided default aspnetdb database is created.
  5. Click the confirm settings and finish button to create the database store.
Preparing to build the security system for use in application, we need to configure the membership provider in web.config file. The following settings for Forms Authentication, Membership and Role provider are applied in the web.config file.

Forms Authentication Settings:


The authentication mode under system.web tag is set to “Forms” and the elements included in are loginUrl, defaultUrl, timeout, cookieless and protection which specifies the login page url, default page url, cookie expiration time and protection level respectively. The settings in web.config file would look similar to code shown below:
 <authentication mode="Forms">
      <forms cookieless="UseCookies" defaultUrl="HomePage.aspx"
        loginUrl="UnAuthorized.aspx" protection="All" timeout="30">
              </forms>
 </authentication>
    

Membership Provider settings:


Some of the important elements to be considered in the Membership provider are name – name of the provider, type – namespace of the provider, connectionStringName – name of the connectionstring and the most important password format. The password format is available in three formats, Hashed, Encrypted and Clear. Hashed format provides one way of storing password in encrypted format which cannot be brought back to original state, whereas Encrypted format provides both to encrypt and decrypt the password.
<membership defaultProvider="Demo_MemberShipProvider">
   <providers>
    <add name="Demo_MemberShipProvider" 
        type="System.Web.Security.SqlMembershipProvider" 
        connectionStringName="cnn" 
        enablePasswordRetrieval="false" 
        enablePasswordReset="true" 
        requiresQuestionAndAnswer="true" 
        applicationName="/" 
        requiresUniqueEmail="false" 
        passwordFormat="Hashed" 
        maxInvalidPasswordAttempts="5" 
        minRequiredPasswordLength="5" 
        minRequiredNonalphanumericCharacters="0" 
        passwordAttemptWindow="10" passwordStrengthRegularExpression="">
   </providers>
</membership>

Role provider settings:


The similar way is to specify the settings for default Provider under system.web tag of the web.config file as shown below. The settings are simple and self explanatory.
>
<roleManager enabled="true" cacheRolesInCookie="true" cookieName="TBHROLES" 
   defaultProvider="TBH_RoleProvider">
              <providers>
                  <add connectionStringName="dld_connectionstring" 
                  applicationName="/" name="TBH_RoleProvider" 
                  type="System.Web.Security.SqlRoleProvider, System.Web, 
                  Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
             </providers>
</roleManager>
In the login.aspx and Registration.aspx pages , we need use the providers to complete the membership system for the application.

Registering The Users

Registration page for the users can be easily created by using the available create user wizard and the following event handlers:
    
    protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
    {
         MembershipCreateStatus p = MembershipCreateStatus.Success;
         Membership.CreateUser(CreateUserWizard1.UserName,  
         CreateUserWizard1.Password, CreateUserWizard1.Email, 
         CreateUserWizard1.Question, CreateUserWizard1.Answer, true, out p);
    }

    protected void CreateUserWizard1_ContinueButtonClick(object sender, EventArgs e)
    {
      Response.Redirect("login.aspx");
    }
 

Authenticate the Users:

The users can be authenticated by using the login_Authenticate event of the Login control. The code to authenticate users goes here:
    protected void Login1_Authenticate(object sender,AuthenticateEventArgs e)
    {
     if (Membership.ValidateUser(Login1.UserName, Login1.Password) == true)
        {
         Login1.Visible = true;
         Session["user"] = User.Identity.Name;         
         FormsAuthentication.RedirectFromLoginPage(Login1.UserName, true);
        }
     else
        {
        Response.Write("Invalid Login");
        }
    }

Creating the Admin Panel:

In the Admin Panel the features to Add, Edit, Delete and Assign Roles to users are provided to the administrator. Creating the roles: The following codesnippet shows u to create Roles
    Public void createRoles()
    {
        try
        {
            if (!Roles.RoleExists(txtrolename.Text))
            {
                Roles.CreateRole(txtrolename.Text);
                BindUsers();
                BindRoles();
                Label1.Text = "Role(s) Created Successfully";
            }
            else
            {
                Label1.Text = "Role(s) Already Exists";
            }
        }
        catch (Exception ex)
        {
            Label1.Text = ex.Message;
        }
    }
BindRoles: The BindRoles method is used to bind the available roles in the store to the user control.
public void BindRoles()
    {
        SqlDataAdapter da = new SqlDataAdapter("select RoleName from aspnet_Roles", cnn);
        DataSet ds = new DataSet();
        da.Fill(ds, "Roles");
        lstRoles.DataSource = ds;
        lstRoles.DataTextField = "RoleName";
        lstRoles.DataValueField = "RoleName";
        lstRoles.DataBind();
    }
BindUsers:
The BindUsers method is used to bind the available users in the store to the user control.
public void BindUsers()
    {
        SqlDataAdapter da = new SqlDataAdapter("select UserName from aspnet_users", cnn);
        DataSet ds = new DataSet();
        da.Fill(ds, "Roles");
        lstusers.DataSource = ds;
        lstusers.DataTextField = "UserName";
        lstRoles.DataValueField = "RoleName";
        lstusers.DataBind();
    }
The following methods take username and rolename as parameters.
Assign Roles To User: The available roles can be assigned to the user in the following way.
 private void AssignRoles()
    {
        try
        {
            if (!Roles.IsUserInRole(lstRoles.SelectedItem.Text))
            {
                Roles.AddUserToRole(lstusers.SelectedItem.Text, lstRoles.SelectedItem.Text);
                BindUsers();
                BindRoles();
                Label1.Text = "User Assigned To User Successfully";
            }
            else
            {
                Label1.Text = "Role(s) Already Assigned To User";
            }
        }
        catch (Exception ex)
        {
            Label1.Text = ex.Message;
        }
    }
Remove Roles from the User: You can remove the user from a role in the following manner:
    private void RemoveuserFromRole()
    {
        try
        {
            Roles.RemoveUserFromRole(lstusers.SelectedItem.Text, lstRoles.SelectedItem.Text);
            BindUsers();
            BindRoles();
            Label1.Text = "User Is Removed From The Role Successfully";
        }
        catch (Exception ex)
        {
            Label1.Text = ex.Message;
        }
    }
Delete Roles: The code is used to Delete the existing Roles, if they are not in use.
public void RemoveRole()
{
 try
        {
            Roles.DeleteRole(lstRoles.SelectedItem.Text);
            BindUsers();
            BindRoles();
            Label1.Text = "Role(s) Removed Successfully";
        }
        catch (Exception ex)
        {
            Label1.Text = ex.Message;
        }
}
Restrict the users depending on the roles by using web.config settings as follows.
<authorization
        <allow roles ="Admin"/>
        <deny users ="*"/>
</authorization>
        
In the above code if you write deny users =”*” and then allow roles =”Admin”, It seems to be no difference but the code wouldn’t work for you because writing the deny user =”*” at the beginning would even restrict the admin to acess the folders.
Show/Hide The Menu Items to The Users Depending on Roles:
      if (Roles.IsUserInRole("Admin"))
        {
            Menu1.Items[0].Text = "Admin";
        }
        else
        {
            Menu1.Items[0].Text = "";
        }
        

Conclusion

We have seen an overview of using the out of box providers available to implement the Membership and Roles for the Asp.net Application.For more details about Forms Authenticatin, Membership and Role provider you can refer the following links.
MSDN Library
MSDN Library

No comments:

Post a Comment