Address: http://aspnet.4guysfromrolla.com/articles/053007-1.aspx
[Source code download]
[Translation] Develop your own web site Administration Tool (Website Administration Tool) (2)
Original article released on: 2007.05.30
Author: Dan Clem
Translation: webabcd
Introduction
ASP. NET 2.0 has built-in Web Site Administration Tool (WSAT). You can select "ASP. to start WSAT. However, WSAT only allows you to manage local web sites. When a web site is deployed on a remote web host, WSAT is limited. Therefore, I decided to develop my own WSAT program from scratch. The first part of this series describes the implementation of my custom WSAT program and the user management section.
This article is the second and last part of this series. Here I will explain in detail some of the points not described in the previous article: role management and access rule management. You can download all the code of the WSAT program at the end of this article. For details about how to use my WSAT program in a new or existing web program, refer to the first part of this series of articles) in "use my custom web site management tool (WSAT )". Further, you will learn more about role management and access rule management in my custom WSAT program.
You 'd better have read the first part of this series.
Before reading this article, you 'd better have read the first part of this series of articles ). In the first part, I will introduce the implementation of my custom WSAT program as a whole, in addition, I explained step by step how to use my WSAT program in a new or existing web program. In addition, I also explained how to implement the user management function. You can download all the code of this custom WSAT program at the end of this Article or at the end of the first part of this series of articles.
Role management
The role management section of my custom WSAT program completes the following three tasks:
· Display all roles in the system
· Allows you to delete an existing role.
· Allow New Roles
I put the functions for implementing these three tasks into a web page. The screenshot is as follows:
I used a GridView to display all roles. The GetAllRoles method of the Roles class returns an array of role names (string arrays) in the system ). Besides listing all roles, I also want to display the number of users associated with each role. Therefore, using the GetAllRoles method to return a string array and bind it to the GridView cannot meet my needs, so I decided to construct my own DataTable and use it as the data source of the GridView. I wrote this code into the Page_PreRender method. // Create a DataTable and define its columns
DataTable RoleList = new DataTable ();
RoleList. Columns. Add ("Role Name ");
RoleList. Columns. Add ("User Count ");
// Obtain the role list and the number of users under each role
String [] allRoles = Roles. GetAllRoles ();
Foreach (string roleName in allRoles)
{
Int numberOfUsersInRole = Roles. GetUsersInRole (roleName). Length;
String [] roleRow = {roleName, numberOfUsersInRole. ToString ()};
RoleList. Rows. Add (roleRow );
}
// Bind the DataTable to the GridView
UserRoles. DataSource = RoleList;
UserRoles. DataBind ();
To add a new role to the system, you only need the following line of code: Roles. CreateRole (roleName );
Similarly, only one line of code is required to delete a role: Roles. DeleteRole (roleName );
Note that if a role has one or more users, the default Provider will throw an exception if you want to delete the role. Therefore, when deleting a role, you must first remove all Members from the role. You can call the RemoveUsersFromRole method of the Roles class to do this. This method requires two parameters: the username array and role name of the member to be removed from the role. You can use the GetUsersInRole method to obtain all users under the specified role (a string array containing the user name is returned ).
Access rule management
On the "access rule management" page, a TreeView control is used to display the directory (folder) structure list in the web program. The tree structure is displayed through the code in the PopulateTree () method called by the Page_Load event. (I copied the PopulateTree and AddNodeAndDescendents methods in almost one word from Scott Mitchell's article Using the TreeView Control and a DataList to Create an Online Image Gallery)
To use the "access rule management" function, You need to log on as an administrator. Before giving a detailed explanation, let's take a look at the sentence in the WSAT program that comes with. net: "rules are applied in order. Apply the first rule that meets the conditions, and the permissions in each rule are overwritten ."
The access rule settings are stored in the Web. config file in each folder. You can manually write these Web. config files, or use the WebConfigurationManager class to manage access rules. Pay attention to your ASP. NET program is running under which user of Windows, generally it should be NT Authority \ Network Service user, you must ensure that this user has read and write Web. config File Permission.
On the "access rule management" Page, users with the administrator role can manage access rules for specified folders by clicking the directory tree view on the left. You can add, move, or delete access rules. The access rules of subfolders inherit from their parent folders, but they cannot be changed in subfolders. You can create an access rule by specifying the Deny and Allow actions of a user or role. In this WSAT program, you can set the permissions of the selected user or role, or specify all users (*) or anonymous users (?) .
Add a rule in two steps: first create a rule, and then add it to the web configuration. // Create a rule
AuthorizationRule newRule;
If (ActionAllow. Checked) newRule = new AuthorizationRule (AuthorizationRuleAction. Allow );
Else
NewRule = new AuthorizationRule (AuthorizationRuleAction. Deny );
// Add Rules
If (ApplyRole. Checked & UserRoles. SelectedIndex> 0)
{
NewRule. Roles. Add (UserRoles. Text );
AddRule (newRule );
}
Else if (ApplyUser. Checked & UserList. SelectedIndex> 0)
{
NewRule. Users. Add (UserList. Text );
AddRule (newRule );
}
Else if (ApplyAllUsers. Checked)
{
NewRule. Users. Add ("*");
AddRule (newRule );
}
Else if (ApplyAnonUser. Checked)
{
NewRule. Users. Add ("? ");
AddRule (newRule );
}
The AddRule method is used to access the configuration file of a specified folder and add our permission rules. Private void AddRule (AuthorizationRule newRule)
{
String virtualFolderPath = FolderTree. SelectedValue;
Configuration config = WebConfigurationManager. OpenWebConfiguration (virtualFolderPath );
SystemWebSectionGroup systemWeb = (SystemWebSectionGroup) config. GetSectionGroup ("system. web ");
AuthorizationSection section = (AuthorizationSection) systemWeb. Sections ["authorization"];
Section. Rules. Add (newRule );
Try
{
Config. Save ();
RuleCreationError. Visible = false;
}
Catch (Exception ex)
{
RuleCreationError. Visible = true;
RuleCreationError. text = "<div class = \" alert \ "> An error occurred and the rule was not added. <I> "+ ex. message + "</I> </div> ";
}
}
Moving up or down rules requires us to write more code by ourselves, because. net does not provide a built-in method to implement this function. I used an array to sort rules to complete this task. I think this method is relatively simple, so it is not described in detail. It is mainly to read all the rules from the configuration file and put them in an ArrayList object, at the same time, delete all rules in the configuration file, sort the array according to the user's needs, and then re-write the sorted rules into the configuration file.
How to implement the "access rule summary" Page
Let's develop our own "access rule summary" page, which is not available in the. net built-in WSAT program. Users who belong to the administrator role can view the permissions of the specified role or user in each directory on this page.
On this page, roles and users are selected through the DropDownList control. After you select a role or user, the TreeView control lists all folders in the web program. It is similar to the TreeView control on the "access rule management" page, the difference is that the TreeView control uses red and green labels to indicate the permissions of the selected role or user in a directory. Of course, as you think, Green indicates that the selected role or user has access permissions, while red indicates the opposite. In addition to the red and green labels, the text on the TreeView control also shows why the role or user you selected has such permissions. Through the screenshot below, you can find that the selected user is "Franklin Forester", because he belongs to the "Marketing" role, so he has access to the marketing folder.
Let our custom WSAT program run securely
Now we can port this custom WSAT program to our new or existing web site. To ensure program security, we hope that only the administrator can access it. To implement this function, you need to add two access rules. In my example, I only allow the Administrator role to access the admin folder and deny all other users, as shown in the preceding figure. Note: The rules that allow access by the administrator role must be on the rules that deny access by all users. Otherwise, no one will have permission to access this folder. (If you accidentally make the administrator role unable to access the admin folder, you need to manually modify the Web. config file so that the administrator can access the admin folder of your custom WSAT program .)
Conclusion
Although you can use the built-in web site management tool (WSAT) of ASP. NET 2.0 to manage users, roles, and permissions, the tool can only be used locally and has some functional limitations. Therefore, this article is the first part of this series of articles (Translator's note: Chinese here) to explore how to implement a custom WSAT program. This custom WSAT program can be transplanted to your new or existing ASP. NET web program and can be deployed on a remote server. In addition, to improve the original WSAT program, it also adds some new features.
Happy programming!