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.
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.
<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.
<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.
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.
<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.
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.
The step by step descriptions of the project are given below.
Step 1: First create a project like the solution explorer given below.
Step 2: The Admin folder contains three pages and a configuration file.
- The first page is about how to add Roles for the system. The UI and Code are shown below.
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.
- The second page contains the information to register a new user. The UI and code are shown below.
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.
- The third page is Assign Role to User. The UI and code are shown below.
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.
- Web.config file. The content of the Web.config file are given below.
<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.
- 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.
This page contains no code. Please add necessary functionalities to show the information.
- This folder contains a configuration file. The content of the Web.config file are given below.
<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.
- 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.
This page contains no code. Please add necessary functionalities to show
the information.
- This folder contains a configuration file. The content of the Web.config
file are given below.
<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:
-
http://www.codeproject.com/Articles/661878/Implementation-of-MVC-Patterns-in-ASP-NET-Web-form
-
http://www.codeproject.com/Articles/674959/MVC-Patterns-Active-and-Passive-Model-and-its
-
http://www.codeproject.com/Articles/708568/Create-Database-Tables-for-ASP-NET-Build-in-Member
-
http://www.codeproject.com/Articles/691691/Apply-Here-Map-in-Windows-Phone-HTML-Apps