Blue Theme Orange Theme Green Theme Red Theme
 
Team Foundation Server Hosting
Home | Forums | ASP.NET 2.0 Tutorials | Web Services | How Do I...? | Class Browser | WPF Quick Starts | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Nevron Gauge for SharePoint
Search :       Advanced Search »
Home » Security » Role Management

Role Management

Role management service deals with the authorization i.e. granting access and managing roles of each of the user registered with the web sit

Page Views : 16820
Downloads : 0
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Nevron Gauge for SharePoint
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

As stated before in my article on Membership service, role management service deals with the authorization i.e. granting access and managing roles of each of the user registered with the web site.

 
Unlike Membership service, which can either use the login server controls to achieve the task, role management service does not offer any server controls. All you have are a set of role management APIs within the system.web.security namespace.

 
Since ASP.Net 2.0 has a provider-based model, role management also uses a set of providers for authorization. By default Beta 2 provides support for SQL Express only. For the remaining data stores you have to explicitly create a provider. I’ll be explaining every thing with respect to the SQL Provider that we created earlier for membership provider. To achieve the same, we will be going back to solution that we created earlier.

  
Add the following section to the web.config file:-

 
<roleManager enabled="true" defaultProvider="MySqlRoleProvider" >
<
providers
>
 <
add connectionStringName="MySqlProviderConnection" applicationName="/"
 name="MySqlRoleProvider" type="
System.Web.Security.SqlRoleProvider, System.Web,
Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
"
/>
</
providers
>
</
roleManager
>

Unlike membership service, role manager needs to enabled explicitly for it to work as specified by enabled="true
".

Change the value against the type attribute with what you have in machine.config file as explained before. Also, note the connection string name is same as what we created earlier. For convenience I am re-writing the same.

<connectionStrings>
<
add name="MySqlProviderConnection" connectionString="server=localhost;integrated security = true;database=aspnetdb"
/>
</
connectionStrings
>

aspnetdb is the database which contains table for role managements as well.

Let’s assume you have folder Admin which has certain pages that should be accessible to only to the user with administrator rights. For this follow the following stepsà

1. Create a new web.config file within the Admin folder by right clicking on the folder name and click "Add new Item". Select the web.config file and click Add.

2. Once done, add authorization section so that web.config file within the Admin folder looks something like as stated below à

<?
xml version="1.0"?>
<
configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"
>
<
system.web
>
<
authorization
>
<
allow roles="administrator"
/>
<
deny users="*"
/>
</
authorization
>
</
system.web
>
</
configuration>

3.Now run the ASP.Net website configuration tool once again by navigating to WebsiteàASP.Net configuration from the IDE menu. Once the ASP.Net configuration page opens up in the browser click on the provider tab and select link which states "select a different provider for each feature (Advanced)". Though I have demonstrated this to you earlier, below screenshot shows the new role provider is added to existing list of providers.

Now your web.config file is all set to use role management service.

Create another web "Manage.aspx" within the admin folder of the website solution. It looks something shown below:-

<html xmlns="http://www.w3.org/1999/xhtml" >
<
head runat
="server">
<title>Untitled Page</title
>
</
head
>
<
body
>
<form id="form1" runat="server"> <div
>
<
center
>
<
asp:Label ID="lblRole" Style
="z-index: 168; left: 448px; position: absolute; top: 128px"
Runat="server" Text="Enter Role:" Font-Bold="True" Height="18px" Width="91px"></asp:Label
>
<
asp:Button ID="btnCreate" Style="z-index: 166; left: 448px; position: absolute;top: 168px" Runat="server" Text="Create Role" Width="259px" Height="24px" OnClick="btnCreate_Click" ValidationGroup="CreateRoleValidation"
/>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" Style
="z-index: 172; left: 736px;
position: absolute; top: 128px"
Runat="server" ErrorMessage="Enter the role to created" ControlToValidate
="txtBoxRole"
ValidationGroup="CreateRoleValidation" Height="18px" Width
="187px">
</asp:RequiredFieldValidator
>
<asp:TextBox ID="txtBoxRole" Style
="z-index: 167; left: 552px; position: absolute;
top: 128px"
Runat="server" ValidationGroup="CreateRoleValidation"></asp:TextBox
>
<asp:ListBox ID="lstBoxRoles" Style
="z-index: 169; left: 448px; position: absolute;
top: 208px"
Runat="server" Width="259px" Height="92px" ValidationGroup
="RolesToDeleteGroup">
</asp:ListBox
>
<asp:Button ID="btnRemove" Style
="z-index: 170; left: 448px; position: absolute;
top: 312px"
Runat="server" Text="Remove Role" Width="259px" Height="24px" OnClick="btnRemove_Click" Font-Bold="False" BorderWidth="1px" ValidationGroup="RolesToDeleteGroup"
/>
<asp:Label ID="lblMessage" Style
="z-index: 171; left: 456px; position: absolute; top: 384px"
Runat="server" Text="Label" Visible="False" Height="19px" Width="247px"></asp:Label
>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<asp:RequiredFieldValidator ID="RequiredFieldValidator2" Style="z-index: 173; left: 736px; position: absolute; top: 208px" Runat="server" Height="18px" Width="203px" ValidationGroup
="RolesToDeleteGroup"
ControlToValidate="lstBoxRoles" ErrorMessage="Select the role to be deleted"> </asp:RequiredFieldValidator
>
<
asp:Button ID="btnRemoveRoleWithUser" Style="z-index: 174; left: 448px; position: absolute;top: 344px" Runat="server" Width="259px" Height="24px" Text
="Remove Role with Users"
ValidationGroup="RolesToDeleteGroup" OnClick="btnRemoveRoleWithUser_Click"
/>
</center>
</div
>
</form
>
</
body
>
</
html>

The above code is interface that the user will be presented with when he tries to create a new role or delete role if no user assigned to that role. It also delete role if any user is assigned to it. Please note that when a role is deleted with the users in it, those users would not be deleted from other roles.

When the page is run, it presents the user with the set of existing roles in the listbox.

For that you need to add a page load event with the following code:-

protected void Page_Load(object sender, EventArgs e)
{
if (!Page
.IsPostBack)
{
//Fetch all the avaiable roles from the database
LstBoxDBind();
}
}
void
LstBoxDBind ()
{
//Assigning the Data Source to List Box
lstBoxRoles.DataSource = Roles
.GetAllRoles();
//Binding the List Box
lstBoxRoles.DataBind();
}

Roles in a membership API which has a number of method implemented within it. We will describe them briefly as and when required. If you notice in the code above we have

Roles.GetAllRoles () methodà is used to fetch all the roles from the aspnet_Roles table within the aspnetdb database.

Once all the roles are returned, it is possible that admin would want to add a new role.

Role management’s Role API has a new method CreateRole which takes a single string parameter à Roles.CreateRole(txtBoxRole.Text);

It is likely that admin might try to add a role that already exists within the aspnet_Roles table and therefore this needs to be checked for before role is added to avoid redundant entries. For that we need to use RoleExists () method implemented within the role class. Roles.RoleExists (txtBoxRole.Text) is the method which checks to see if the role already exists in the table. It return a boolean value i.e. true or false.

This is what we are doing is piece of code below. On the button click of create role, it check to see if the role already exists. If it exists, a message is returned back to user prompting the same. In case it does not exist, it creates a new role using the CreateRole () method.

For that Add the following code to Create Role button:-

protected void btnCreate_Click(object sender, EventArgs e)
{
try
{
lblMessage.Text = String
.Empty;
// Check is the Role exists
if (!Roles
.RoleExists(txtBoxRole.Text))
{
// Create Role
Roles
.CreateRole(txtBoxRole.Text);
// Bind the list box again after creating the role
LstBoxDBind ();
//Displaying the message for role creation
lblMessage.Visible = true
;
lblMessage.Text = "Role : '" + Server.HtmlEncode(txtBoxRole.Text.ToString()) + "' created."
;
txtBoxRole.Text = ""
;
}
else
{
lblMessage.Visible = true
;
lblMessage.Text = "Role : '" + Server.HtmlEncode(txtBoxRole.Text.ToString()) + "' already exists."
;

}
catch (Exception
ex)
{
lblMessage.Visible = true
;
lblMessage.Text = ex.Message;
}
}

For deleting roles we have Role API offers following methods:-

à Roles.DeleteRole (String strRole);

This method would delete the role from the aspnet_Roles table in case there are not users assigned to this role. In case users are assigned to this role, then your job would be to remove the users from role and then delete the role. Note that there is difference when we remove users from a role in the fact that the users will be removed only from that specified role and not from the remaining roles.

Add the following piece of code to remove role button click event:-

protected void btnRemove_Click(object sender, EventArgs e)
{
try
{
// Setting the lable for message to invisible
string strRole = String
.Empty;
lblMessage.Text = String
.Empty;
lblMessage.Visible = true
;
strRole = lstBoxRoles.SelectedItem.Value;
//Checking if there are users assigned to a role
if (Roles
.GetUsersInRole(strRole).Length == 0)
{
//Deleting Role
Roles
.DeleteRole(strRole);
lblMessage.Visible = true
;
lblMessage.Text = "Role :'" + Server.HtmlEncode(strRole) + "' deleted."
;
}
else
{
lblMessage.Visible = true
;
lblMessage.Text = "There are users assigned to Role '" + Server.HtmlEncode(strRole) + "'. Select a role and click <b>Remove Role with Users</b> button to delete the role."
;
// Setting the visibility of btnRemoveRoleWithUser to true
}
// Re-bind roles to ListBox.
LstBoxDBind ();
}
catch (Exception
ex)
{
lblMessage.Visible = true
;
lblMessage.Text = ex.Message;
}
}

If you noticed, we have used another method à Roles.GetUsersInRole(string strRole). This method is used to check if the users are contained in that role. If the length of the string is returned is 0, then we can delete the role using Roles.DeleteRole (strRole) method.

In case the length of the string returned is not zero, then we need to remove the users from that role and then delete the role.

Removing users from roles can use any one of the following construct à

Roles.RemoveUserFromRole (string uname, string rolename)

Roles.RemoveUserFromRoles (string uname, string rolenames ())

Roles.RemoveUsersFromRole (string unames (), string rolename)

Roles.RemoveUsersFromRoles (string unames (), string rolenames ())

In our code, we want to remove users from that role and then delete the role. Therefore, we would be using the third construct à

Roles.RemoveUsersFromRole(Roles.GetUsersInRole(strRole), strRole);

You can add the logic to the button " remove role with users" and embed the construct appropriately wherever applicable. And then delete the role using the Roles.DeleteRole (strRole); method

Managing Roles

Next we are going to discuss how to manage users and roles. That is, how to assign user to role and how to remove the user from role.

The source code for this page is :-

<html xmlns="http://www.w3.org/1999/xhtml" >
<
head runat
="server">
<title>Untitled Page</title
>
</
head
>
<
body
>
<form id="form1" runat
="server">
<asp:DropDownList ID="cboUser" Style="z-index: 166; left: 392px; position: absolute; top: 168px" Runat="server" Width="150px" Height="18px" DataSourceID="SqlDataSource1" DataTextField="UserName" DataValueField="UserName" OnSelectedIndexChanged="cboUser_SelectedIndexChanged" AutoPostBack="True" OnDataBound
="cboUser_DataBound">
</asp:DropDownList
>
<
asp:Button ID="BtnDeleteRoles" Style
="z-index: 172; left: 552px; position: absolute; top: 208px"
Runat="server" Height="24px" Width="131px" Text="Delete Roles" OnClick="btnDeleteRoles_Click"
/>
&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;
&nbsp;
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:aspnetdbConnectionString %>
"
SelectCommand="SELECT * FROM [vw_aspnet_Users]"></asp:SqlDataSource
>
<asp:Label ID="lblUser" Style
="z-index: 170; left: 280px; position: absolute; top: 168px"
Runat="server" Text="Select a User" Font-Bold="True" Height="18px" Width="99px"></asp:Label
>
<asp:Label ID="lblExistingRole" Style
="z-index: 171; left: 272px; position: absolute; top: 208px"
Runat="server" Text="Existing Roles" Font-Bold="True" Height="18px" Width="107px"></asp:Label><asp:Label ID="lblAllRoles" Style="z-index: 171; left: 272px; position: absolute; top: 344px"
Runat="server" Text="Available Roles" Font-Bold="True" Height="18px" Width="107px"></asp:Label
>
<asp:Button ID="btnAddRole" Style
="z-index: 173; left: 552px; position: absolute; top: 344px"
Runat="server" Height="24px" Width="131px" Text="Add Role" OnClick="btnAddRoles_Click"
/>
<asp:Label ID="lblMessage" Style
="z-index: 178; left: 440px; position: absolute; top: 464px"
Runat="server" Visible="False"></asp:Label
>
<asp:ListBox ID="lstBoxExistingRoles" Style
="z-index: 180; left: 392px; position: absolute;
top: 208px"
Runat="server" Height="100px" Width="150px" SelectionMode
="Multiple">
</asp:ListBox>
&nbsp;
<asp:ListBox ID="lstBoxAllRoles" Style="z-index: 175; left: 392px; position: absolute; top: 344px" Runat="server" Height="100px" Width="150px" SelectionMode="Multiple"
>
</asp:ListBox>
&nbsp;&nbsp;&nbsp;
</form
>
</
body
>
</
html>

On this page, we have a drop down box which is binded to the SQL data source which in return uses a select query to fetch all the users from aspnet_Users table within the aspnetdb database. In the page_load event we bind the list box with all the Available roles. The code for the same is below :-

protected void Page_Load(object sender, EventArgs e)
{
// Binding the ListBox containing all available roles
if (!Page.IsPostBack)
{
lstBoxAllRoles.DataSource = Roles.GetAllRoles();
lstBoxAllRoles.DataBind();
}
}  

Below method gets called as soon after the page is loaded but before the controls are rendered on the page. It fetches all the roles for the first user in the drop down list.

protected void cboUser_DataBound(object sender, EventArgs e)
{
//Bind the listBox containing existing roles of a user
lstBoxExistingRoles.DataSource = Roles.GetRolesForUser(cboUser.SelectedValue);
lstBoxExistingRoles.DataBind();
 

Now, when Admin selects any of the users from the drop down box, we would want to see the roles that are already assigned to him/her. For this we add SelectedIndexChanged event on the drop down list as stated under:-

protected void cboUser_SelectedIndexChanged(object sender, EventArgs e)
{
//Bind the listBox containing existing roles of user on selection
// change of user combo box
lstBoxExistingRoles.DataSource = Roles.GetRolesForUser(cboUser.SelectedValue);
lstBoxExistingRoles.DataBind();
}

Before we go any further, look at the various constructs for adding the users:-

Roles.AddUserToRole (string uname, string rolename) à Add user to a role

Roles.AddUsersToRole (string unames (), string rolename) à Add multiple users to a role

Roles.AddUserToRoles (string uname, string rolenames ()) à Add a user to multiple roles

Roles.AddUsersToRoles (string unames (), string rolenames ()) à Add multiple users to multiple roles

To add a user to particular role, add the following code to the Add role button click event.This code checks to see if the user already exists in that particular role which is selected in the second list box against Add Role button. If the role is already assigned to a user, then it prompts for the same. Else the role would be assigned to user using the first construct described above.

protected void btnAddRoles_Click(object sender, EventArgs e)
{
// For each selected role in the available role listBox,
// assign the user to this role
foreach (ListItem role in lstBoxAllRoles.Items)
{
if (role.Selected == true)
{
// Before assigning the role to a User
// Check if the role already exists for the user
if (!Roles
.IsUserInRole(cboUser.SelectedValue, role.ToString()))
{
lblMessage.Visible = true;
Roles
.AddUserToRole(cboUser.SelectedValue, role.ToString());
lblMessage.Text = cboUser.SelectedValue + " assigned role of " + Server.HtmlEncode(role.ToString());
lstBoxExistingRoles.DataSource = Roles.GetRolesForUser(cboUser.SelectedValue);
lstBoxExistingRoles.DataBind();
}
else
{
lblMessage.Visible = true;
lblMessage.Text = " " + cboUser.SelectedValue + "already has role '" + Server.HtmlEncode(role.ToString()) + "' assigned";
}
}
}
}

Similarly, if you want to remove user from one or more roles you can go ahead using any of the below constructs:-

Roles.RemoveUserFromRole (string uname, string rolename)

Roles.RemoveUserFromRoles (string uname, string rolenames ())

Roles.RemoveUsersFromRole (string unames (), string rolename)

Roles.RemoveUsersFromRoles (string unames (), string rolenames ())

In the code below, we are doing through the items in the list box and removing the user from a particular role. Add the following code to the delete role button click event.

protected void btnDeleteRoles_Click(object sender, EventArgs e)
{
// For each selected role in the Existing Role ListBox
// remove the user from the Role
foreach (ListItem role in lstBoxExistingRoles.Items)
{
if (role.Selected == true)
{
Roles
.RemoveUserFromRole(cboUser.SelectedValue, role.ToString());
}
}
// Bind the ListBox containing Existing roles of a User again
lstBoxExistingRoles.DataSource = Roles.GetRolesForUser(cboUser.SelectedValue);
lstBoxExistingRoles.DataBind();
}

This is all I had to discuss to in this article. You can drill into the details more by getting a good hold of these basics and moving on to advanced concepts.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Anubhav Bansal
Anubhav Bansal is a Microsoft Certified Application Developer(MCAD) and Microsoft Certified Technology Sepcialist and has been working in Microsoft Technologies for more than 5 years. Anubhav has extensive experience in developing web based applications and client -server applications. For past 1 year, Anubhav has been working on developing Online Service Delivery applications using Windows Communication Foundation. Also equipped with the knowledge on MVP(Model viewer Presentation) design pattern and thread safe singleton patterns.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
Team Foundation Server Hosting
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.