Role Manager Add Role: Roles Defined: C# protected void Page_Loadobject sender, EventArgs e { if !Page.IsPostBack { ListBoxDataBind; } } protected void Button1_Clickobject sende
Trang 1defaultProvider="AspNetSqlRoleProvider"
createPersistentCookie="false"
maxCachedResults="25">
<providers>
<clear />
<add connectionStringName="LocalSqlServer" applicationName="/"
name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider,
System.Web, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a" />
<add applicationName="/" name="AspNetWindowsTokenRoleProvider"
type="System.Web.Security.WindowsTokenRoleProvider, System.Web,
Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</providers>
</roleManager>
The role management service defines its settings from within themachine.config.commentsfile, as
shown in the previous code listing You can make changes to these settings either directly in the
machine.configfile or by overriding any of the higher level settings you might have by making changes
in theweb.configfile (thereby making changes only to the application at hand)
The main settings are defined in the<roleManager>element Some of the attributes of the
<roleManager>element are defined in the following table
application This attribute takes aBooleanvalue and is set toFalseby default This means that the role management service is disabled by default This is done to avoid breaking changes that would occur for users migrating from ASP.NET 1.0/1.1 to ASP.NET 2.0 or 3.5 Therefore, you must first change this value toTruein either themachine.configor the
web.configfile
cacheRolesInCookie Defines whether the roles of the user can be stored within a cookie on the
client machine This attribute takes aBooleanvalue and is set toTrueby default This is an ideal situation because retrieving the roles from the cookie prevents ASP.NET from looking up the roles of the user via the role management provider Set it toFalseif you want the roles to be retrieved via the provider for all instances
cookieName Defines the name used for the cookie sent to the end user for role
management information storage By default, this cookie is named
.ASPXROLES, and you probably will not change this
cookieTimeout Defines the amount of time (in minutes) after which the cookie expires
The default value is30minutes
cookieRequireSSL Defines whether you require that the role management information be sent
over an encrypted wire (SSL) instead of being sent as clear text The default value isFalse
Trang 2Attribute Description
cookieSliding-Expiration
Specifies whether the timeout of the cookie is on a sliding scale The default value isTrue This means that the end user’s cookie does not expire until 30 minutes (or the time specified in thecookieTimeoutattribute) after the last request to the application has been made If the value of the
cookieSlidingExpirationattribute is set toFalse, the cookie expires
30 minutes from the first request
createPersistent-Cookie
Specifies whether a cookie expires or if it remains alive indefinitely The default setting isFalsebecause a persistent cookie is not always advisable for security reasons
cookieProtection Specifies the amount of protection you want to apply to the cookie stored
on the end user’s machine for management information The possible settings includeAll,None,Encryption, andValidation You should always attempt to useAll
defaultProvider Defines the provider used for the role management service By default, it is
set toAspNetSqlRoleProvider
Making Changes to the web.config File
The next step is to configure yourweb.configfile so that it can work with the role management service
Certain pages or subsections of your application may be accessible only to people with specific roles To
manage this access, you define the access rights in theweb.configfile The necessary changes are shown
in Listing 16-29
Listing 16-29: Changing the web.config file
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<roleManager enabled="true"/>
<authentication mode="Forms" />
<authorization>
<deny users="?" />
</authorization>
</system.web>
<location path="AdminPage.aspx">
<system.web>
<authorization>
<allow roles="AdminPageRights" />
<deny users="*" />
</authorization>
</system.web>
</location>
</configuration>
Trang 3Thisweb.configfile is doing a couple of things First, the function of the first < system.web > section
is no different from that of the membership service shown earlier in the chapter The<deny>element is denying all unauthenticated users across the board
The second section of thisweb.configfile is rather interesting The<location>element is used to
define the access rights of a particular page in the application (AdminPage.aspx) In this case, only users contained in theAdminPageRightsrole are allowed to view the page, but all other users — regardless
of whether they are authenticated — are not allowed to view the page When using the asterisk (*) as a value of theusersattribute of the<deny>element, you are saying that all users (regardless of whether they are authenticated) are not allowed to access the resource being defined This overriding denial of
access, however, is broken open a bit via the use of the<allow>element, which allows users contained within a specific role
Adding and Retrieving Application Roles
Now that themachine.configor theweb.configfile is in place, you can add roles to the role manage-ment service The role managemanage-ment service, just like the membership service, uses data stores to store
information about the users These examples focus primarily on using Microsoft SQL Server Express
Edition as the provider because it is the default provider
One big difference between the role management service and the membership service is that no server
controls are used for the role management service You manage the application’s roles and the user’s role details through a Roles API or through the Web Site Administration Tool provided with ASP.NET 3.5
Listing 16-30 shows how to use some of the new methods to add roles to the service
Listing 16-30: Adding roles to the application
VB
<%@ Page Language="VB" %>
<script runat="server">
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
If Not Page.IsPostBack Then
ListBoxDataBind() End If
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Roles.CreateRole(TextBox1.Text)
ListBoxDataBind()
End Sub
Protected Sub ListBoxDataBind()
ListBox1.DataSource = Roles.GetAllRoles()
ListBox1.DataBind()
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Role Manager</title>
Continued
Trang 4<body>
<form id="form1" runat="server">
<h1>Role Manager</h1>
Add Role:<br />
<asp:TextBox ID="TextBox1" Runat="server"></asp:TextBox>
<p><asp:Button ID="Button1" Runat="server" Text="Add Role to Application"
OnClick="Button1_Click" /></p>
Roles Defined:<br />
<asp:ListBox ID="ListBox1" Runat="server">
</asp:ListBox>
</form>
</body>
</html>
C#
<%@ Page Language="C#" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ListBoxDataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Roles.CreateRole(TextBox1.Text.ToString());
ListBoxDataBind();
}
protected void ListBoxDataBind()
{
ListBox1.DataSource = Roles.GetAllRoles();
ListBox1.DataBind();
}
</script>
This example enables you to enter roles into the text box and then to submit them to the role
manage-ment service The roles contained in the role managemanage-ment service are then displayed in the list box, as
illustrated in Figure 16-22
To enter the roles into the management service, you simply use theCreateRole()method of theRoles
class As with theMembershipclass, you do not instantiate theRolesclass To add roles to the role
man-agement service, use theCreateRole()method that takes only a single parameter — the name of the role
as aStringvalue:
Roles.CreateRole(rolename As String)
With this method, you can create as many roles as you want, but each role must be unique — otherwise
an exception is thrown
Trang 5Figure 16-22
To retrieve the roles that are in the application’s role management service (such as the list of roles
displayed in the list box from the earlier example), you use theGetAllRoles()method of theRoles
class This method returns aStringcollection of all the available roles in the service:
Roles.GetAllRoles()
Deleting Roles
It would be just great to sit and add roles to the service all day long Every now and then, however, you might want to delete roles from the service as well Deleting roles is just as easy as adding roles to the
role management service To delete a role, you use one of theDeleteRole()method signatures The first option of theDeleteRole()method takes a single parameter — the name of the role as aStringvalue The second option takes the name of the role plus aBooleanvalue that determines whether to throw
an exception when one or more members are contained within that particular role (so that you don’t
accidentally delete a role with users in it when you don’t mean to):
Roles.DeleteRole(rolename As String)
Roles.DeleteRole(rolename As String, throwOnPopulatedRole As Boolean)
Listing 16-31 is a partial code example that builds on Listing 16-30 For this example, add an additional button, which initiates a second button-click event that deletes the role from the service
Trang 6Listing 16-31: Deleting roles from the application
VB
Protected Sub DeleteButton_Click(ByVal sender As Object, _
ByVal e As System.EventArgs)
For Each li As ListItem In ListBox1.Items
If li.Selected = True Then
Roles.DeleteRole(li.ToString()) End If
Next
ListBoxDataBind()
End Sub
C#
protected void DeleteButton_Click(object sender, EventArgs e)
{
foreach (ListItem li in ListBox1.Items) {
if (li.Selected == true) {
Roles.DeleteRole(li.ToString());
}
}
ListBoxDataBind();
}
This example deletes the selected items from the ListBox control If more than one selection is made
(meaning that you have placed the attributeSelectionMode = "Multiple"in the ListBox control), each
of the roles is deleted from the service, in turn, in theFor Eachloop AlthoughRoles.DeleteRole(li
.ToString())is used to delete the role,Roles.DeleteRole(li.ToString(), True)could also be used
to make sure that no roles are deleted if that role contains any members
Adding Users to Roles
Now that the roles are in place and it is possible to delete these roles if required, the next step is adding
users to the roles created A role does not do much good if no users are associated with it To add a single
user to a single role, you use the following construct:
Roles.AddUserToRole(username As String, rolename As String)
To add a single user to multiple roles at the same time, you use this construct:
Roles.AddUserToRoles(username As String, rolenames() As String)
To add multiple users to a single role, you use the following construct:
Roles.AddUsersToRole(usernames() As String, rolename As String)
Then, finally, to add multiple users to multiple roles, you use the following construct:
Roles.AddUsersToRoles(usernames() As String, rolenames() As String)
Trang 7The parameters that can take collections, whether they areusernames()orrolenames(), are presented to the method asStringarrays
Getting All the Users of a Particular Role
Looking up information is easy in the role management service, whether you are determining which
users are contained within a particular role or whether you want to know the roles that a particular user belongs to
Methods are available for either of these scenarios First, look at how to determine all the users contained
in a particular role, as illustrated in Listing 16-32
Listing 16-32: Looking up users in a particular role
VB
<%@ Page Language="VB" %>
<script runat="server">
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
If Not Page.IsPostBack Then
DropDownDataBind() End If
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
GridView1.DataSource = Roles.GetUsersInRole(DropDownList1.SelectedValue)
GridView1.DataBind()
DropDownDataBind()
End Sub
Protected Sub DropDownDataBind()
DropDownList1.DataSource = Roles.GetAllRoles()
DropDownList1.DataBind()
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Role Manager</title>
</head>
<body>
<form id="form1" runat="server">
Roles:
<asp:DropDownList ID="DropDownList1" Runat="server">
</asp:DropDownList>
<asp:Button ID="Button1" Runat="server" Text="Get Users In Role"
OnClick="Button1_Click" />
<br />
<br />
<asp:GridView ID="GridView1" Runat="server">
</asp:GridView>
</form>
Trang 8</html>
C#
<%@ Page Language="C#" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DropDownDataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
GridView1.DataSource = Roles.GetUsersInRole(DropDownList1.SelectedValue);
GridView1.DataBind();
DropDownDataBind();
}
protected void DropDownDataBind()
{
DropDownList1.DataSource = Roles.GetAllRoles();
DropDownList1.DataBind();
}
</script>
This page creates a drop-down list that contains all the roles for the application Clicking the button
displays all the users for the selected role Users of a particular role are determined using the
GetUsersIn-Role()method This method takes a single parameter — aStringvalue representing the name of
the role:
Roles.GetUsersInRole(rolename As String)
When run, the page looks similar to the page shown in Figure 16-23
Figure 16-23
Trang 9Getting All the Roles of a Particular User
To determine all the roles for a particular user, create a page with a single text box and a button In the text box, you type the name of the user; and a button click initiates the retrieval and populates a GridView control The button click event (where all the action is) is illustrated in Listing 16-33
Listing 16-33: Getting all the roles of a specific user
VB
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
GridView1.DataSource = Roles.GetRolesForUser(TextBox1.Text)
GridView1.DataBind()
End Sub
C#
protected void Button1_Click(object sender, EventArgs e)
{
GridView1.DataSource = Roles.GetRolesForUser(TextBox1.Text.ToString());
GridView1.DataBind();
}
The preceding code produces something similar to what is shown in Figure 16-24
Figure 16-24
To get the roles of a particular user, you simply use theGetRolesForUser()method This method has
two possible signatures The first is shown in the preceding example — aStringvalue that represents
the name of the user The other option is an invocation of the method without any parameters listed This returns the roles of the user who has logged in to the membership service
Removing Users from Roles
In addition to adding users to roles, you can also easily remove users from roles To delete or remove a single user from a single role, you use the following construct:
Roles.RemoveUserFromRole(username As String, rolename As String)
Trang 10To remove a single user from multiple roles at the same time, you use this construct:
Roles.RemoveUserFromRoles(username As String, rolenames() As String)
To remove multiple users from a single role, you use the following construct:
Roles.RemoveUsersFromRole(usernames() As String, rolename As String)
Then, finally, to remove multiple users from multiple roles, you use the following construct:
Roles.RemoveUsersFromRoles(usernames() As String, rolenames() As String)
The parameters shown as collections, whether they areusernames()orrolenames(), are presented to
the method asStringarrays
Checking Users in Roles
One final action you can take is checking whether a particular user is in a role You can go about this in a
couple of ways The first is using theIsUserInRole()method
TheIsUserInRole()method takes two parameters — the username and the name of the role:
Roles.IsUserInRole(username As String, rolename As String)
This method returns aBooleanvalue on the status of the user, and it can be used as shown
in Listing 16-34
Listing 16-34: Checking a user’s role status
VB
If (Roles.IsUserInRole(TextBox1.Text, "AdminPageRights")) Then
’ perform action here
End If
C#
if (Roles.IsUserInRole(TextBox1.Text.ToString(), "AdminPageRights"))
{
// perform action here
}
The other option, in addition to theIsUserInRole()method, is to useFindUsersInRole() This method
enables you make a name search against all the users in a particular role TheFindUsersInRole()method
takes two parameters — the name of the role and the username, both asStringvalues:
Roles.FindUsersInRole(rolename As String, username As String)
Listing 16-35 shows an example of this method