Click here to Skip to main content
13,353,106 members (55,291 online)
Click here to Skip to main content
Add your own
alternative version


61 bookmarked
Posted 10 Nov 2011

ASP.NET Membership and Role Provider

, 27 Nov 2011
Rate this:
Please Sign up or sign in to vote.
Brief description of how to use the available Membership and Role Provider available in ASP.NET


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 allow 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 you are 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 steps given below 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.

Step 1:

Step 2:

Step 3:

Step 4:

Step 5:

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 the code shown below:

<authentication mode="Forms">
     <forms cookieless="UseCookies" defaultUrl="HomePage.aspx" 

	loginUrl="UnAuthorized.aspx" protection="All" timeout="30">

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">
		<add name="Demo_MemberShipProvider"












		    passwordAttemptWindow="10" passwordStrengthRegularExpression="">

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="Demo_RoleProvider">
                  <add connectionStringName="dld_connectionstring"

                  applicationName="/" name="Demo_RoleProvider"

                  type="System.Web.Security.SqlRoleProvider, System.Web,
                  Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>

In the login.aspx and Registration.aspx pages, we need to 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;
		CreateUserWizard1.Password, CreateUserWizard1.Email,
     CreateUserWizard1.Question, CreateUserWizard1.Answer, true, out p);

protected void CreateUserWizard1_ContinueButtonClick(object sender, EventArgs e)

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);
        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 code snippet shows you how to create Roles:

Public void createRoles()
        if (!Roles.RoleExists(txtrolename.Text))
            Label1.Text = "Role(s) Created Successfully";
            Label1.Text = "Role(s) Already Exists";
    catch (Exception ex)
        Label1.Text = ex.Message;


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";


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";

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()
            if (!Roles.IsUserInRole(lstRoles.SelectedItem.Text))
                Label1.Text = "User Assigned To User Successfully";
                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()
        Roles.RemoveUserFromRole(lstusers.SelectedItem.Text, lstRoles.SelectedItem.Text);
        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()
            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:


        <allow roles ="Admin"/>
        <deny users ="*"/>

In the above code, if you write deny users =”*” and then allow roles =”Admin”, there 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 access the folders.

Show/Hide The Menu Items to The Users Depending on Roles

if (Roles.IsUserInRole("Admin"))
    Menu1.Items[0].Text = "Admin";
    Menu1.Items[0].Text = "";


We have seen an overview of using the out of the box providers available to implement the Membership and Roles for the ASP.NET Application. For more details about Forms Authentication, Membership and Role provider, you can refer to the following links:


  • 9th November, 2011: Initial version
  • 27th November, 2011: Updated code and added images to the article


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

S V Saichandra
Software Developer Collabera
Singapore Singapore
S V Sai Chandra is a Software Engineer from Hyderabad Deccan. He started Embedded Programing in his college days and now he is a Web Developer by Profession. He Loves coding and his passion has always been towards Microsoft Technologies. Apart from coding his other hobbies include reading books, painting and hang out with friends is his most favorite past time hobby.
He blogs at
Technical Skills:
C#,Ado.Net,Asp.Net,Sql Server,JavaScript,XML,Web services.

You may also be interested in...


Comments and Discussions

GeneralMy vote of 4 Pin
Vikash Kumar24-Jul-17 21:18
memberVikash Kumar24-Jul-17 21:18 
QuestionIt is very useful resources about Membership and Role provider available in ASP.Net Pin
Zack Mathews5-Oct-16 1:52
memberZack Mathews5-Oct-16 1:52 
GeneralA network-related or instance-specific error occurred while establishing a connection to SQL Server. Pin
GaneshNeedArticle5-Jan-16 14:01
memberGaneshNeedArticle5-Jan-16 14:01 
Questionhow to add pages in role wise Pin
pandurangpawar7@gmail.com22-Sep-15 20:17
memberpandurangpawar7@gmail.com22-Sep-15 20:17 
Questiondoubts Pin
Member 1090999330-Jun-14 3:54
memberMember 1090999330-Jun-14 3:54 
QuestionAutomatically setting up Roles Pin
Member 914293614-Nov-13 8:16
memberMember 914293614-Nov-13 8:16 
QuestionHelpful for me. Pin
sachin2398810-Oct-13 3:47
membersachin2398810-Oct-13 3:47 
QuestionRequired help to fix the setup issue Pin
Member 103097164-Oct-13 8:02
memberMember 103097164-Oct-13 8:02 
Questionfor data base Pin
r28001411-Sep-13 0:43
memberr28001411-Sep-13 0:43 
Questioni am having this error in aspnet_regsql.exe Pin
r28001411-Sep-13 0:40
memberr28001411-Sep-13 0:40 
AnswerASP.NET Membership and Role Provider Pin
ch.haiderali15-Jun-13 14:23
memberch.haiderali15-Jun-13 14:23 
GeneralMy vote of 4 Pin
Mishraniraj211-Apr-13 23:05
memberMishraniraj211-Apr-13 23:05 
Questionyour script d'ont work Pin
elfigho26-Dec-12 6:52
memberelfigho26-Dec-12 6:52 
Questiongood work.. very detailed Pin
sanamshaikh3-Jul-12 2:03
membersanamshaikh3-Jul-12 2:03 
QuestionWhere is the Profile? Pin
rojinromina23-Apr-12 20:58
memberrojinromina23-Apr-12 20:58 
AnswerRe: Where is the Profile? Pin
S V Saichandra23-Apr-12 23:25
memberS V Saichandra23-Apr-12 23:25 
GeneralRe: Where is the Profile? Pin
rojinromina26-Apr-12 0:16
memberrojinromina26-Apr-12 0:16 
GeneralRe: Where is the Profile? Pin
S V Saichandra2-May-12 6:56
memberS V Saichandra2-May-12 6:56 
QuestionWhat's up with your avatar?! Pin
Thesisus18-Apr-12 13:21
memberThesisus18-Apr-12 13:21 
QuestionCodefile missing for DemoProfileProvider.aspx Pin
jeremygrand27-Nov-11 7:22
memberjeremygrand27-Nov-11 7:22 
AnswerRe: Codefile missing for DemoProfileProvider.aspx Pin
S V Saichandra27-Nov-11 8:28
memberS V Saichandra27-Nov-11 8:28 
Dont worry guys. I have updated the article and the code. You we will get the updated in a day or two. Thanks.!

AnswerRe: Codefile missing for DemoProfileProvider.aspx Pin
S V Saichandra27-Nov-11 9:06
memberS V Saichandra27-Nov-11 9:06 
QuestionMissing DemoProfileProvider.aspx.cs. Did you download and build by yourself? Pin
Joe Chen26-Nov-11 16:08
memberJoe Chen26-Nov-11 16:08 
QuestionHave a 3: More of a Beginner Intro Pin
Dewey10-Nov-11 9:50
memberDewey10-Nov-11 9:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.180111.1 | Last Updated 27 Nov 2011
Article Copyright 2011 by S V Saichandra
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid