1. Trang chủ
  2. » Công Nghệ Thông Tin

Professional ASP.NET 3.5 in C# and Visual Basic Part 85 ppt

10 62 0

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Nội dung

Evjen c16.tex V2 - 01/28/2008 2:51pm Page 797 Chapter 16: Membership and Role Management cookieProtection="All" defaultProvider="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 the machine.config.comments file, as shown in the previous code listing. You can make changes to these settings either directly in the machine.config file or by overriding any of the higher level settings you might have by making changes in the web.config file (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. Attribute Description enabled Defines whether the role management service is enabled for the application. This attribute takes a Boolean value and is set to False by 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 to True in either the machine.config or the web.config file. cacheRolesInCookie Defines whether the roles of the user can be stored within a cookie on the client machine. This attribute takes a Boolean value and is set to True by 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 to False if 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 is 30 minutes. 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 is False . 797 Evjen c16.tex V2 - 01/28/2008 2:51pm Page 798 Chapter 16: Membership and Role Management Attribute Description cookieSliding- Expiration Specifies whether the timeout of the cookie is on a sliding scale. The default value is True . This means that the end user’s cookie does not expire until 30 minutes (or the time specified in the cookieTimeout attribute) after the last request to the application has been made. If the value of the cookieSlidingExpiration attribute is set to False , 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 is False because 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 include All , None , Encryption ,and Validation . You should always attempt to use All . defaultProvider Defines the provider used for the role management service. By default, it is set to AspNetSqlRoleProvider . Making Changes to the web.config File The next step is to configure your web.config file 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 the web.config file. 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 > 798 Evjen c16.tex V2 - 01/28/2008 2:51pm Page 799 Chapter 16: Membership and Role Management This web.config file 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 this web.config file 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 the AdminPageRights role 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 ( * )asa value of the users attribute 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 the machine.config or the web.config file is in place, you can add roles to the role manage- ment service. The role management 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 799 Evjen c16.tex V2 - 01/28/2008 2:51pm Page 800 Chapter 16: Membership and Role Management < /head > < 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 management 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 the CreateRole() method of the Roles class. As with the Membership class, you do not instantiate the Roles class. To add roles to the role man- agement service, use the CreateRole() method that takes only a single parameter — the name of the role as a String value: 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. 800 Evjen c16.tex V2 - 01/28/2008 2:51pm Page 801 Chapter 16: Membership and Role Management Figure 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 the GetAllRoles() method of the Roles class. This method returns a String collection 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 the DeleteRole() method signatures. The first option of the DeleteRole() method takes a single parameter — the name of the role as a String value. The second option takes the name of the role plus a Boolean value 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. 801 Evjen c16.tex V2 - 01/28/2008 2:51pm Page 802 Chapter 16: Membership and Role Management Listing 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 attribute SelectionMode = "Multiple" in the ListBox control), each of the roles is deleted from the service, in turn, in the For Each loop. Although Roles.DeleteRole(li .ToString()) is used to delete the role, Roles.DeleteRole(li.ToString(), True) couldalsobeused 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) 802 Evjen c16.tex V2 - 01/28/2008 2:51pm Page 803 Chapter 16: Membership and Role Management The parameters that can take collections, whether they are usernames() or rolenames() , are presented to the method as String arrays. 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 > Continued 803 Evjen c16.tex V2 - 01/28/2008 2:51pm Page 804 Chapter 16: Membership and Role Management < /body > < /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 — a String value 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 804 Evjen c16.tex V2 - 01/28/2008 2:51pm Page 805 Chapter 16: Membership and Role Management Getting 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 the GetRolesForUser() method.Thismethodhas two possible signatures. The first is shown in the preceding example — a String value 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) 805 Evjen c16.tex V2 - 01/28/2008 2:51pm Page 806 Chapter 16: Membership and Role Management To 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 are usernames() or rolenames() , are presented to the method as String arrays. 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 the IsUserInRole() method. The IsUserInRole() method takes two parameters — the username and the name of the role: Roles.IsUserInRole(username As String, rolename As String) This method returns a Boolean value 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 the IsUserInRole() method, is to use FindUsersInRole() . This method enables you make a name search against all the users in a particular role. The FindUsersInRole() method takes two parameters — the name of the role and the username, both as String values: Roles.FindUsersInRole(rolename As String, username As String) Listing 16-35 shows an example of this method. 806 . as String arrays. 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. 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. 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 to True in either the machine.config or the web.config file. cacheRolesInCookie Defines

Ngày đăng: 05/07/2014, 19:20