Using the Role Manager


Instead of configuring authorization for particular users, you can group users into roles and assign authorization rules to the roles. For example, you might want to password-protect a section of your website so that only members of the Administrators role can access the pages in that section.

Like ASP.NET Membership, the Role Manager is built on the existing ASP.NET authentication framework. You configure role authorization rules by adding an authorization element to one or more web configuration files.

Furthermore, like ASP.NET Membership, the Role Manager uses the provider model. You can customize where role information is stored by configuring a particular Role provider.

The ASP.NET Framework includes three role providers:

  • SqlRoleProvider Enables you to store role information in a Microsoft SQL Server database.

  • WindowsTokenRoleProvider Enables you to use Microsoft Windows groups to represent role information.

  • AuthorizationStoreRoleProvider Enables you to use Authorization Manager to store role information in an XML file, Active Directory, or Activity Directory Application Mode (ADAM).

In the following sections, you learn how to configure each of these Role providers. You also learn how to manage role information programmatically by working with the Roles application programming interface.

Configuring the SqlRoleProvider

The SqlRoleProvider is the default role provider. You can use the SqlRoleProvider to store role information in a Microsoft SQL Server database. The SqlRoleProvider enables you to create custom roles. You can make up any roles that you need.

You can use the SqlRoleProvider with either Forms authentication or Windows authentication. When Forms authentication is enabled, you can use ASP.NET Membership to represent users and assign the users to particular roles. When Windows authentication is enabled, you assign particular Windows user accounts to custom roles. I assume, in this section, that you are using Forms authentication.

Warning

The Web Site Administration Tool does not support assigning users to roles when Windows authentication is enabled. When Windows authentication is enabled, you must assign users to roles programmatically.


The web configuration file in Listing 21.27 enables the SqlRoleProvider.

Listing 21.27. Web.Config

<?xml version="1.0" encoding="utf-8"?> <configuration>     <system.web>         <roleManager enabled="true" />         <authentication mode="Forms" />     </system.web> </configuration> 

The Role Manager is disabled by default. The configuration file in Listing 21.27 simply enables the Role Manager. Notice that the configuration file also enables Forms authentication.

If you don't want to type the file in Listing 21.27, you can let the Web Site Administration Tool create the file for you. Open the Web Site Administration Tool in Visual Web Developer by selecting the menu option Website, ASP.NET Configuration. Next, click the Security tab and click the Enable roles link (see Figure 21.11).

Figure 21.11. Enabling Roles with the Web Site Administration Tool.


After you enable the Role Manager, you need to create some roles. You can create roles in two ways. You can use the Web Site Administration Tool or you can create the roles programmatically.

Open the Web Site Administration Tool and click the Create or Manage Roles link located under the Security tab. At this point, you can start creating roles. I'll assume that you have created a role named Managers.

After you create a set of roles, you need to assign users to the roles. Again, you can do this by using the Web Site Administration Tool or you can assign users to roles programmatically.

If you have not created any users for your application, create a user now by clicking the Create User link under the Security tab. Notice that you can assign a user to one or more roles when you create the user (see Figure 21.12). You can click the Create or Manage Roles link to assign roles to users at a later date.

Figure 21.12. Assigning a new user to a role.


After you finish creating your roles and assigning users to the roles, you can use the roles in the authentication section of a web configuration file. For example, imagine that your web site includes a folder named SecretFiles and you want only members of the Managers role to be able to access the pages in that folder. The web configuration file in Listing 21.28 blocks access to anyone except members of the Managers role to the SecretFiles folder.

Listing 21.28. Web.Config

<?xml version="1.0"?> <configuration>     <system.web>       <authorization>         <allow roles="Managers"/>         <deny users="*"/>       </authorization>     </system.web> </configuration> 

The configuration file in Listing 21.28 authorizes Managers and denies access to everyone else.

If you prefer, you can manage authorization with the Web Site Administration Tool. Behind the scenes, this tool creates web configuration files that contain authorization elements (in other words, it does the same thing as we just did).

Under the Security tab, click the Create Access Rules link. Select the SecretFiles folder from the tree view, select the Managers role, and select Allow (see Figure 21.13). Click the OK button to create the rule. Next, create a second access rule to deny access to users not in the Managers role. Select the SecretFiles folder, select All Users, and select Deny. Click the OK button to add the new rule.

Figure 21.13. Creating authorization rules.


Using a Different Database with the SqlRoleProvider

By default, the SqlRoleProvider uses the same Microsoft SQL Server Express database as ASP.NET Membership: the AspNetDB.mdf database. This database is created for you automatically in your application's root App_Data folder.

If you want to store role information in another Microsoft SQL Server database, then you must perform the following two configuration steps.

  • Configure the database so that it contains the necessary database objects.

  • Configure your application to use the new database.

Before you can store role information in a database, you need to add the necessary tables and stored procedures to the database. The easiest way to add these objects is to use the aspnet_regsql command-line tool. This tool is located in the following folder:

\WINDOWS\Microsoft.NET\Framework\[version] 


Note

You don't need to navigate to the Microsoft.NET folder when you open the SDK Command Prompt.


If you execute aspnet_regsql without any parameters, then the ASP.NET SQL Server Setup Wizard opens (see Figure 21.14). You can use this wizard to connect to a database and add the necessary database objects automatically.

Figure 21.14. Using the SQL Server Setup Wizard.


Alternatively, you can set up a database by executing the following two SQL batch files.

  • InstallCommon.sql

  • InstallRoles.sql

These batch files are located in the same folder as the aspnet_regsql tool.

After you set up your database, you need to configure a new SqlRoleProvider that includes the proper connection string for your database. The web configuration file in Listing 21.29 configures a new provider named MyRoleProvider that connects to a database named MyDatabase located on a server named MyServer.

Listing 21.29. Web.Config

[View full width]

<?xml version="1.0" encoding="utf-8"?> <configuration>   <connectionStrings>     <add       name="MyConnection"       connectionString="Data Source=MyServer; Integrated Security=True;Initial  Catalog=MyDatabase"/>   </connectionStrings>   <system.web>       <authentication mode="Forms" />       <roleManager enabled="true" defaultProvider="MyRoleProvider">         <providers>           <add             name="MyRoleProvider"             type="System.Web.Security.SqlRoleProvider"             connectionStringName="MyConnection"/>         </providers>       </roleManager>   </system.web> </configuration> 

The configuration file in Listing 21.29 creates a new default RoleManager named MyRoleProvider. Notice that the MyRoleProvider provider includes a connectionStringName attribute that points to the MyConnection connection.

Configuring the WindowsTokenRoleProvider

When you use the WindowsTokenRoleProvider, roles correspond to Microsoft Windows groups. You must enable Windows authentication when using the WindowsTokenRoleProvider. You cannot use Forms authentication or ASP.NET Membership with the WindowsTokenRoleProvider.

The configuration file in Listing 21.30 configures the WindowsTokenRoleProvider as the default provider.

Listing 21.30. Web.Config

<?xml version="1.0" encoding="utf-8"?> <configuration>     <system.web>       <authentication mode="Windows" />       <roleManager enabled="true" defaultProvider="MyRoleProvider">         <providers>           <add             name="MyRoleProvider"             type="System.Web.Security.WindowsTokenRoleProvider" />         </providers>       </roleManager>     </system.web> </configuration> 

The page in Listing 21.31 contains a LoginView control. The LoginView control displays different content to the members of the Windows Administrators group than it displays to everyone else (see Figure 21.15).

Figure 21.15. Displaying different content to members of the Windows Administrators group.


Listing 21.31. ShowWindowsRoles.aspx

<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head  runat="server">     <title>Show Windows Roles</title> </head> <body>     <form  runat="server">     <div>     <asp:LoginView                  Runat="server">         <RoleGroups>         <asp:RoleGroup Roles="BUILTIN\Administrators">             <ContentTemplate>             <h1>Welcome Administrator!</h1>             </ContentTemplate>         </asp:RoleGroup>         </RoleGroups>         <LoggedInTemplate>             <h1>Welcome Average User!</h1>         </LoggedInTemplate>     </asp:LoginView>     </div>     </form> </body> </html> 

If you request the page in Listing 21.31 after enabling the WindowsTokenRoleProvider, then you see the content displayed by the LoginView control only when you are a member of the Windows Administrators group.

Configuring the AuthorizationStoreRoleProvider

Authorization Manager (AzMan) is a component of Windows Server 2003. You can use Authorization Manager to define roles, tasks, and operations.

Authorization Manager supports more features than the authorization framework included in the ASP.NET Framework. For example, Authorization Manager supports role inheritance, which enables you to easily define new roles based on existing roles.

Note

You can use Authorization Manager with Windows XP Professional. However, you must install it first. You need to download the Windows Server 2003 Administrative Tools Pack from the Microsoft MSDN website (msdn.microsoft.com).


Authorization Manager can store role information in three different ways. You can create an authorization store by using an XML file, by using Active Directory, or by using Active Directory Application Mode (ADAM).

Before you use Authorization Manager with the ASP.NET Framework, you need to create an authorization store. Role information is stored in an XML file local to the application. Follow these steps:

1.

Launch Authorization Manager by executing the command AzMan.msc from a command prompt (see Figure 21.16).

2.

Switch Authorization Manager into Developer mode by selecting the menu option Action, Options and selecting Developer mode.

3.

Open the New Authorization Store dialog box by selecting the menu option Action, New Authorization Store.

4.

Select the XML file option and enter the path to your application's App_Data folder for the Store Name field. For example:

c:\Websites\MyWebsite\App_Data\WebRoles.xml 


5.

Create a new Authorization Manager application by right-clicking the name of your authorization store and selecting New Application. Enter the name WebRoles for your application (you can leave the other fields blank).

Figure 21.16. Using Authorization Manager.


After you complete these steps, a new XML file is added to your application. This XML file contains the authorization store.

Next, you need to configure the ASP.NET Role Manager to use the authorization store. The web configuration file in Listing 21.32 uses the WebRoles.xml authorization store.

Listing 21.32. Web.Config

<?xml version="1.0" encoding="utf-8"?> <configuration>   <connectionStrings>     <add       name="AZConnection"       connectionString="msxml://~/App_Data/WebRoles.xml"/>   </connectionStrings>   <system.web>     <authentication mode="Windows" />     <roleManager enabled="true" defaultProvider="MyRoleProvider">       <providers>         <add           name="MyRoleProvider"           type="System.Web.Security.AuthorizationStoreRoleProvider"           connectionStringName="AZConnection"           applicationName="WebRoles"             />       </providers>     </roleManager>   </system.web> </configuration> 

You should notice a couple of things about the configuration file in Listing 21.32. First, notice that the connection string uses the prefix msxml: to indicate that the connection string represents a connection to an XML file.

Second, notice that the AuthorizationStoreRoleProvider includes an applicationName attribute. This attribute must contain the name of the Authorization Manager application that you created in the preceding steps.

After you complete these configuration steps, you can use the Authorization Manager just as you do the default SqlMembershipProvider. You can define new roles by using either the Web Site Administration Tool or the Authorization Manager interface (see Figure 21.17).

Figure 21.17. Creating a new role definition with Authorization Manager.


Caching Roles in a Browser Cookie

To improve your application's performance, you can cache user roles in a browser cookie. That way, the Role Manager does not have to perform a query against the Role provider each and every time a user visits a page.

Caching roles in cookies is disabled by default. You can enable this feature with the web configuration file in Listing 21.33.

Listing 21.33. Web.Config

<?xml version="1.0" encoding="utf-8"?> <configuration>     <system.web>       <roleManager         enabled="true"         cacheRolesInCookie="true"         createPersistentCookie="true" />     </system.web> </configuration> 

The web configuration in Listing 21.33 enables role caching. Furthermore, it causes the roles to be cached in a persistent cookie rather than a session cookie.

Warning

When you cache roles in a cookie, there is the potential that a user's cached roles can become out of sync with a user's actual roles. If you update a user's roles on the server, they don't get updated on the browser. You can call the Roles.DeleteCookie() method to delete the cached cookies.


You can set a number of attributes that are related to the roles cookie:

  • cacheRolesInCookie Enables you to cache user roles in a browser cookie (the default value is false).

  • cookieName Enables you to specify the name for the roles cookie (the default value is .ASPXROLES).

  • cookiePath Enables you to specify the path associated with the cookie (the default value is /).

  • cookieProtection Enables you to encrypt and validate the roles cookie. Possible values are All, Encryption, None, and Validation (the default value is All).

  • cookieRequireSSL Enables you to require that the roles cookie be transmitted over a Secure Sockets Layer connection (the default value is false).

  • cookieSlidingExpiration Enables you to prevent a cookie from expiring just as long as a user continues to request pages (the default value is true).

  • cookieTimeout Enables you to specify the amount of time in minutes before a cookie times out (the default value is 30).

  • createPersistentCookie Enables you to create a persistent rather than a session cookie (the default value is false).

  • domain Enables you to specify the domain associated with the cookie (the default value is an empty string).

  • maxCachedResults Enables you to specify the maximum number of roles that are cached in a cookie (the default is 25).

Using the Roles Application Programming Interface

The Roles class exposes the main application programming interface for manipulating roles. If you need to create roles programmatically, delete roles, or assign users to roles, then you use the methods of the Roles class.

The Roles class includes the following methods:

  • AddUsersToRole Enables you to add an array of users to a role.

  • AddUsersToRoles Enables you to add an array of users to an array of roles.

  • AddUserToRole Enables you to add a user to a role.

  • AddUserToRoles Enables you to add a user to an array of roles.

  • CreateRole Enables you to create a new role.

  • DeleteCookie Enables you to delete the roles cookie.

  • DeleteRole Enables you to delete a particular role.

  • FindUsersInRole Enables you to return a list of users in a role that has a particular username.

  • GetAllRoles Enables you to retrieve a list of all roles.

  • GetrolesForUser Enables you to get a list of all roles to which a user belongs.

  • GetUsersInRole Enables you to get a list of users in a particular role.

  • IsUserInRole Enables you to determine whether a particular user is a member of a particular role.

  • RemoveUserFromRole Enables you to remove a particular user from a particular role.

  • RemoveUserFromRoles Enables you to remove a particular user from an array of roles.

  • RemoveUsersFromRole Enables you to remove an array of users from a particular role.

  • RemoveUsersFromRoles Enables you to remove an array of users from an array of roles.

  • RoleExists Enables you to determine whether a particular role exists.

The page in Listing 21.34 illustrates how you can use the methods of the Roles class. The Page_Load() method creates two roles named Sales and Managers (if they don't already exist). Next, it assigns the current user to both roles. The body of the page contains a GridView that displays all the roles to which the current user belongs (see Figure 21.18).

Figure 21.18. Displaying a user's roles.


Listing 21.34. ShowRoles.aspx

<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server">     Sub Page_Load()         ' If user is not authenticated, redirect to Login page         If Not Request.IsAuthenticated Then             FormsAuthentication.RedirectToLoginPage()             Response.End()         End If         ' Create two roles         If Not Roles.RoleExists("Managers") Then             Roles.CreateRole("Managers")         End If         If Not Roles.RoleExists("Sales") Then             Roles.CreateRole("Sales")         End If         ' Add current user to both roles         If Not Roles.IsUserInRole("Managers") Then             Roles.AddUserToRole(User.Identity.Name, "Managers")         End If         If Not Roles.IsUserInRole("Sales") Then             Roles.AddUserToRole(User.Identity.Name, "Sales")         End If     End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head  runat="server">     <title>Show Roles</title> </head> <body>     <form  runat="server">     <div>     <h1>Your Roles</h1>     <asp:GridView                  DataSource         EmptyDataText="You are not a member of any roles"         GridLines="none"         Runat="server" />     <asp:ObjectDataSource                  TypeName="System.Web.Security.Roles"         SelectMethod="GetRolesForUser"         Runat="server" />     </div>     </form> </body> </html> 




ASP. NET 2.0 Unleashed
ASP.NET 2.0 Unleashed
ISBN: 0672328232
EAN: 2147483647
Year: 2006
Pages: 276

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net