Click here to Skip to main content
15,891,687 members
Articles / Web Development / ASP.NET

Easy way to learn the Asp.Net Built in Membership and Role using custom controls with example

Rate me:
Please Sign up or sign in to vote.
4.60/5 (20 votes)
11 Mar 2014CPOL6 min read 60.6K   3.8K   40   8
Built in Membership and Role for Authentication and Authorization

Introduction

In this tutorial I tried to describe the Built in Membership and Role for Authentication and Authorization with diagram and example. It also shows how to apply Membership and Role using custom controls and built in APIs in an Asp.Net web project.

Contents list of this tutorial
  • Define Authentication and Authorization.
  • Membership in details.
  • Role in details.
  • Create database tables for Membership and Role.
  • Sample Project to apply Membership and Role.

Part-1: Define Authentication and Authorization

Authentication: In short authentication is the process of validating the user id and password to give access to resources of a site.

Authorization: In short authorization is the process of giving the permission to authenticated user to access the restricted resources of the site.

Part-2: Membership in details

Asp.net Membership is a built in process to validate the user credential. It works with FormAuthentication to allow user to validate and save the authentication token for the next request.

One way we can apply Membership using built in Login control. In this case Login control handles the functionality to authenticate the user and save the authentication token.

The other way to apply the Membership is using the Login page with asp.net controls like TextBox and Button, and handles the authentication using the Membership’s built in APIs.

To work with Membership we must have to activate the Membership in web.config file and have to select the Authentication mode to “Form”. If we don’t make the Authentication mode to Form, by default the Windows Authentication mode will be activated. In this case Membership will now work.

I tried to represent the Membership graphically with the following diagram of my own.

Image 1

In the above diagram when a user tries to login then Membership check for valid user. If the user is valid then user can access the resources otherwise he is redirected to the Login page again.

Part-3: Role in details

Role management is used to manage the authorization. We can manage the authorization in two ways.

  • Apply access rules to individual user to restrict the access to resources.
  • Apply access rules to Roles so that users of the same Role can get access to the allocated resources for that Role.

Example of access rules to individual user are shows below.

XML
<authorization>  
   <deny users="?" />
</authorization> 

Above xml code segment of the project web.config file indicates that unauthenticated

users are denied to access the pages of the application.

XML
<authorization>  
  <allow users="admin1" />   
  <deny users="*" />
</authorization>

Above xml code segment of a web.config file inside a folder indicates that only “admin1” user is allowed to access the pages inside the folder and other user are denied. In this technique for every new user addition, this configuration file must need to be updated.

Role management is useful when there is huge number of Users. In this case every user will be under a Role and the access rules are applied to Roles.

Using Role manager we can also programmatically hide or show the part of the pages by checking the User Role. The way to check the Role shows below.

C#
if (User.IsInRole("members"))
{
   totalWorker.Visible = True;
}

Or we can apply rules to a folder to allow or deny access to the files of the folder. We can do this in the following ways.

XML
<configuration>
  <location path="Manager">
    <system.web>
      <authorization>
        <allow roles="Manager" />
        <deny users="*" />
      </authorization>
    </system.web>
  </location>
<configuration>

The above example shows, we can configure the Manager folder so that User of the Manager Role only can access the resources of this folder and other users are denied. If an unauthorized user tries to view a restricted page, the user is redirected to a Login page.

I tried to represent the Membership and Role together graphically with the following diagram of my own.

Image 2

The above diagram shows that users of same color are in same Role. Here users of different Roles (Admin, Manager and Worker) have the access permission of respective folder (Admin, Manager and Worker). And User of any Roles must need to login to access the resources.

Part-4: Create database tables for Membership and Role

Before going to create a sample project we need to create a Database and some necessary table to store Membership and Role. Details for creating necessary tables for Membership and Role, please read my article http://www.codeproject.com/Articles/708568/Create-Database-Tables-for-ASP-NET-Build-in-Member .

Part-5: Sample Project to apply Membership and Role

Project summary: This sample project is an Asp.Net project shows how the Membership and Role works. This project contains some Folder with pages in it and rules to access the resources inside the folders. These applied rules ensure that users of the permitted Roles can access the resources.

The Default UI of this project is shows below.

Image 3

The step by step descriptions of the project are given below.

Step 1: First create a project like the solution explorer given below.

Image 4

Step 2: The Admin folder contains three pages and a configuration file.

  1. The first page is about how to add Roles for the system. The UI and Code are shown below.

    Image 5

    C#
    public partial class AddRole : System.Web.UI.Page
       {
           protected void Page_Load(object sender, EventArgs e)
           {
               if (!Page.IsPostBack)
               {
                   DisplayRolesInGrid();
               }
           }
           private void DisplayRolesInGrid()
           {
               grdRoleList.DataSource = Roles.GetAllRoles();
               grdRoleList.DataBind();
           }
           protected void btnCreateRole_Click(object sender, EventArgs e)
           {
               string newRoleName = txtRoleName.Text.Trim();
               if (!Roles.RoleExists(newRoleName))
               {
                   Roles.CreateRole(newRoleName);
                   DisplayRolesInGrid();
               }
               txtRoleName.Text = string.Empty;
           }
           protected void grdRoleList_RowDeleting(object sender, GridViewDeleteEventArgs e)
           {
               Label RoleNameLabel = grdRoleList.Rows[e.RowIndex].FindControl("RoleNameLabel") as Label;
               Roles.DeleteRole(RoleNameLabel.Text, false);
               DisplayRolesInGrid();
           }
       }
    

    Code Description: RoleExists() function checks, is the same Rule is exist in database given by user. If given Role name is not exist then CreateRole() function creates the role in the database using the default provider given in the configuration file.

  2. The second page contains the information to register a new user. The UI and code are shown below.

    Image 6

    C#
    public partial class RegisterUser : System.Web.UI.Page
        {
     
            protected void Page_Load(object sender, EventArgs e)
            {
            }
            protected void btnCreateUser_Click(object sender, EventArgs e)
            {
                try
                {
                    MembershipUser newUser = Membership.CreateUser(txtUserName.Text, txtPassword.Text, txtEmail.Text);
                    if (Membership.ValidateUser(txtUserName.Text, txtPassword.Text))
                    {
                        FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, false);
                    }
                    else
                    {
                        Msg.Text = "Fail to Register";
                    }
                }
                catch (Exception ex)
                {
                    Msg.Text = "Passwork is not strong";
                }
            }
        }

    Code Description: CreateUser() function of the object Membership is used to create a User in the database. Then the ValidateUser() function is used to check the existence of the User and takes the user in Login state. RedirectFromLoginPage() function of FormsAuthentication is used to create a authentication token.

  3. The third page is Assign Role to User. The UI and code are shown below.

    Image 7

    C#
    public partial class UserToRole : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!Page.IsPostBack)
                {
                    BindList();
                    DisplayUserRolesInGrid();
                }
            }
            private void DisplayUserRolesInGrid()
            {
                using (CustomMembershipEntities dataContext = new CustomMembershipEntities())
                {
                    var UserRole = (from u in dataContext.aspnet_Users.Include("aspnet_Roles")
                                    from r in u.aspnet_Roles
                                    where r != null
                                    select new { User = u, Role = r }).ToList();
                    grdUserRoles.DataSource = UserRole.ToArray();
                    grdUserRoles.DataBind();
                }
            }
            private void BindList()
            {
                foreach (var role in Roles.GetAllRoles())
                {
                    ddlRole.Items.Add(new ListItem(role, role));
                }
                foreach (MembershipUser user in Membership.GetAllUsers())
                {
                    ddlUser.Items.Add(new ListItem(user.UserName, user.UserName));
                }
            }
            protected void btnRoleAssign_Click(object sender, EventArgs e)
            {
                string roleName = ddlRole.SelectedItem.Text;
                string userName = ddlUser.SelectedItem.Text;
                if (!User.IsInRole(roleName))
                {
                    Roles.AddUserToRole(userName, roleName);
                }
            }
        }

    Code Description: IsInRole() function of User object check is the user is already assigned to the selected role. If not assigned then AddUserToRole() function of Roles object assign role to the selected user.

  4. Web.config file. The content of the Web.config file are given below.
    C#
    <configuration>
      <system.web>
        <authorization>
          <allow roles="Admin" />
          <deny users="*" />
        </authorization>
      </system.web>
    </configuration>

    XML Description: This xml segment indicates that the resources of this folder are allowed to access by those Users who has an Admin Role and all the other Users are denied.

Step 3: The Manager folder contains one page and a configuration file.

  1. The first page is a dashboard for Manager Role Users. To access the page the user need to Login as a Member Role. The UI and code are shown below.

    Image 8

    This page contains no code. Please add necessary functionalities to show the information.

  2. This folder contains a configuration file. The content of the Web.config file are given below.
    XML
    <configuration>
      <system.web>
        <authorization>
          <allow roles="Manager" />
          <deny users="*" />
        </authorization>
      </system.web>
    </configuration>

    XML Description: This xml segment indicates that the resources of this folder are allowed to access by those Users who has an Manager Role and all the other Users are denied.

Step 4: The Worker folder contains one page and a configuration file.

  1. The page is used by the worker to save the daily information of him. To
    access the page the user need to Login as a Worker Role. The UI and code are shown
    below.

    Image 9This page contains no code. Please add necessary functionalities to show
    the information.

  2. This folder contains a configuration file. The content of the Web.config
    file are given below.
    XML
    <configuration>
      <system.web>
        <authorization>
          <allow roles="Worker" />
          <deny users="*" />
        </authorization>
      </system.web>
    </configuration>

    XML Description: This xml segment indicates that the resources of this folder are allowed to access by those Users who has an Worker Role and all the other Users are denied.

Conclusion

These are all about the Asp.Net built in Membership and Role. Hope it will help you to get some idea about Asp.Net Authentication and Authorization. The attached file contains both the project and the database backup.

My Published Articles:

  1. http://www.codeproject.com/Articles/661878/Implementation-of-MVC-Patterns-in-ASP-NET-Web-form
  2. http://www.codeproject.com/Articles/674959/MVC-Patterns-Active-and-Passive-Model-and-its
  3. http://www.codeproject.com/Articles/708568/Create-Database-Tables-for-ASP-NET-Build-in-Member
  4. http://www.codeproject.com/Articles/691691/Apply-Here-Map-in-Windows-Phone-HTML-Apps

License

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


Written By
Founder http://softwarelandmarks.com/
Bangladesh Bangladesh
I am in Software Development for more than 12 years. I am expert on Microsoft Platform for Web Forms, MVC, MVC Core, Web API, Desktop App, PHP etc. I am also expert on jQuery, AngularJS, Bootstrap, Font Awesome, Telerik UI, Kendo UI etc. I know BackboneJS, KnockoutJS also. I am an article writer. I have many articles in CodeProject.

Email: khademulbasher@gmail.com

Comments and Discussions

 
GeneralMy vote of 3 Pin
Nitin Choudhary15-Jan-16 3:15
Nitin Choudhary15-Jan-16 3:15 
Questionwas delete Pin
jalloee21-Dec-14 22:13
jalloee21-Dec-14 22:13 
QuestionGood article - I think it is exactly what I am looking for. I want to maintain the aspnetdb database outside the Visual Studio working environment. Pin
Member 1060758116-Apr-14 17:50
Member 1060758116-Apr-14 17:50 
QuestionBad zip file for CustomMembershipRole-noexe.zip Pin
rward019-Apr-14 5:00
rward019-Apr-14 5:00 
Questionhi good post, but the Create Database tables for Membership,Roles article is deleted Pin
franva00817-Mar-14 3:13
franva00817-Mar-14 3:13 
Questionlanguage Pin
thewazz10-Mar-14 12:44
professionalthewazz10-Mar-14 12:44 
QuestionVote of 4 Why not the identity model (claim based)? Pin
Member 995921210-Mar-14 3:34
Member 995921210-Mar-14 3:34 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun9-Mar-14 19:16
Humayun Kabir Mamun9-Mar-14 19:16 
Nice...

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.