"Reprint" "Rights control" role access dynamically generate User Rights menu tree

Source: Internet
Author: User
Tags datetime md5 reserved trim versions ticket
"Reprint" "Rights control" role access dynamically generate User Rights menu tree Blog Category:Universal Component Design


reprint: http://www.comprg.com.cn/post_show.asp?id=7873

Author: Anonymous

First, Introduction

With the introduction of the. NET and the Java EE Development platform, the traditional software development model has been changed to B/s mode, which puts forward higher requirements for the security of the system, and in B/S mode, due to the particularity of HTTP protocol and browser, it may cause information leakage and even make the illegal user modify the data. However, the setting, allocation and management of authority are essential functions of any system. How to design and implement its functions, there are many schemes, the traditional access control method DAC (discretionary access control, autonomous access controller model), MAC (Mandatory access controls, Mandatory access control model is difficult to meet the needs of complex enterprise environments. In this paper, the popular role-based access control (RBAC, role Based access controls) of the basic ideas, skillfully using the Web control treeview and ASP., designed in B/s mode, according to different users, different role permissions, A concrete implementation method of dynamically generating User menu tree.

This paper introduces the basic idea of RBAC, and gives the implementation method in ASP.

second, the basic idea of role access control (RBAC)



Figure 1 The basic idea of RBAC

In RBAC, license permissions (privilege) is the right to allow execution on one or more objects, and the role is the set of permissions, as shown in Figure 1. The basic idea of RBAC is to divide the whole access process into two steps: the access permission and the role Association, the role is associated with the user, thus realizes the logical separation between the user and the access permission.

RBAC's authorization to access permission is managed by the system administrator, and the system administrator defines different roles according to the different positions in the organization, and the user is assigned the corresponding role according to their functions and responsibilities. Once a user becomes a member of a role, the user can complete the functions that the role has.

Because RBAC realizes the logical separation of user and access rights, it greatly facilitates the complexity of the rights management. Users can be associated with the role according to the actual work of the user, on the one hand to define roles, increase the user in the deletion role easy to operate, on the other hand, you can change the permissions of the role to achieve high-volume user rights update. In real-world applications, changes in roles/permissions are much slower than changes between users/roles, and when a user's position is changed, simply remove the user's current role and join the role that represents the new job. Therefore, the advantages of RBAC are obvious, more in line with the application characteristics of enterprises.

Third, User rights menu tree

Using the TreeView control to dynamically implement the user rights menu tree is based on the basic principle of Role access control (RBAC), assigning users different roles, each role corresponding to some permissions, and then based on the user ID to get the user's corresponding set of roles, the role collection to get the corresponding set of permissions, The permission collection is then used by the Treewiew control to dynamically generate a permission tree that consists of a page (module) that the user's corresponding role can access. In this way, the user does not have access to the page in the Permissions menu tree will not appear, different user access to different interfaces, the implementation of user rights unified management.

The following aspects from the functional module design, database design, architecture design, etc. to illustrate its implementation process.

1. Function Module Division

 

Figure 2 User Rights management function module diagram

User Rights management system functions as shown in Figure 2, wherein the main module functions are described as follows:

User Management module is divided into: delete users, browse users and Role Assignment three sub-modules, mainly responsible for the deletion of various types of users, authentication and assigning roles for users. User Management module does not increase the functionality of the user sub-module, mainly by the user registration module to achieve.

The Rights Management module consists of two sub-modules: role management and access control. Role management is responsible for the management of various roles (add, delete, change), to give the role of the corresponding Information Service module use Rights, remove the role of a module of the use of rights, etc. access control is the key to ensure the security of information, when the user logged on after authentication, The system automatically generates the access permission set according to the use rights of the information Service module that the user has the role, which enables the user to access the authorized information and intercept the access to the unauthorized information service.

2. Database Design

In the implementation of RBAC to generate User Rights menu tree, in order to improve system management and data access efficiency, in the Database Design user table (table 1), the Role table (table 2), the User Role table (table 3), the role of the Permission table (table 4) and the menu tree structure table (table 5) A total of 5 tables.

Table 1 User Information table users

Field name

Type

Field Chinese name

Userid

Int

User ID primary key

UserName

Varchar (50)

User name

Password

Varchar (100)

User password

Encrypt with MD5

Realname

Varchar (50)

User's real name

Email

Varchar (100)

User Email

State

Int

User status, default: 0

Baoliu

Char (1)

Reserved, default: 1

Table 2 Role Information table roles

Field name

Type

Field Chinese name

Roleid

Int

Role ID PRIMARY key

RoleName

Varchar (20)

Role name

Encrypt with MD5

Roledesc

Varchar (50)

Role description

PerMission

Varchar (50)

Role Permissions

Baoliu

Char (1)

Reserved, default: 1

Table 3 User Role Table Userroles

Field name

Type

Field Chinese name

Roleid

Int

Role ID

Userid

Int

User ID

Table 4 Role Permissions Table Rolepermissions

Field name

Type

Field Chinese name

Roleid

Int

Role ID

Treeid

Int

Menu ID

ParentID

Int

Parent Menu ID

Table 5 menu tree Structure table tree

Field name

Type

Field Chinese name

Treeid

Int

Menu ID PRIMARY key

Title

Varchar (200)

Menu Title

Desn

Text (16)

Menu Description

ParentID

Int (4)

Menu Parent ID

Url

Varchar (200)

Menu link Address

In the WEB program, the system function module is organized into a tree structure, each module corresponding to a menu, the parent-child relationship between the menus directly reflects the parent-child relationship between the modules, in the database with a table tree to store this structure.

The relationship of 5 tables is shown in Figure 3.

Figure 3 diagram between 5 tables

3. System Architecture Design

b/S mode, using three-layer structure: The presentation layer, the logic layer and the data layer. For the convenience of programming, the data layer is divided into the entity layer and the data access layer, and the code of opening, shutting down the database and calling the stored procedure is all sealed in the data access class SQLHelper.cs. The actual application is a four-layer structure, the system architecture design is shown in Figure 4.

Figure 4 User Rights Management architecture diagram

Note: The arrows in Figure 4 are call relationships.

In order to improve the execution efficiency of the program, all data operations are implemented through the class SQLHelper.cs call stored procedure.

Several main classes and key methods of the entity layer are as follows:

(1) User class:

Getuserlogin (String susername,string spassword): User Login verification.

Getrolebyuser (int Nuserid): Returns the user-owned set of roles by the user ID.

Adduserrole (int nuserid,int nroleid):

Assign roles to users.

getuserpermissionlist (int UserID): Gets all the user's permission sets.

(2) Role class Roleentity:

Addrolemodule (int ntreeid,int nroleid): Assign permissions to the role.

Deleterolemodule (int nroleid): Removes the permissions that the role has.

Getmodulebyrole (int Nroleid): Gets the permission set for the role by the role ID.

(3) Permission tree type:

Bindtree (TreeView treeview,int UserID): Build tree directory.

Createchildnode (TreeNode parentnode,datatable DataTable): Recursive functions generate tree nodes.

Gettreesbyuserid (int nuserid): The user permission set is dynamically generated by the user ID of the user permission tree.

(4) User Rights check class Ckeckauthority:

chkpermission (int UserID): Checks whether the user has access rights.

IsInRole (int Roleid): Checks if the role exists.

4. Specific implementation

In the tree structure, the role of the authorization to take a simple way, each authorization, the corresponding Roleid, Treeid and parentid into the Rolepermissions table, see Figure 5.

Figure 5 Role authorization

To implement a dynamically generated User menu tree, Microsoft's IE Web control (available for free download to Microsoft Web site) must be installed in the ASP. After the installation is complete, reference Microsoft.Web.UI.WebControls.dll in the development environment, IE Web controls such as Mutipage, TabStrip, Toobar, and TreeView will appear in the toolbox of the development environment.

Add the IE Web control treeview to the Web page in the following two steps:

(1) Add the following @register instructions at the top of the page:

<% @Register tagprefix= "IEWC"

Namespace= "Microsoft.Web.UI.WebControls"

Assembly= "Microsoft.Web.UI.WebControls"%>

(2) Add the following Web control syntax in the Web page where you want the TreeView to appear:

<iewc:treeview runat= "Server" ...>

...

</iewc:treeview>

For the use of the TreeView control, readers can refer to the corresponding book.

The overall schema page includes two sections of user login (longin.aspx) and the main interface (Default.aspx).

The main interface is divided into three parts: the upper part is the title bar (head.aspx), the left part is the menu tree (lefttree.aspx), and the right part is the main frame (mainfram.aspx). Where the Lefttree.aspx page contains the TreeView control, the user clicks the menu node in the tree to open the appropriate action page.

User login adopts the window posture authentication, which is responsible for providing the user's authentication. Then, according to the role played by the user in the system, take out the user's corresponding permission set, dynamically generate the user corresponding to the system's Operation permission tree (see Figure 6).



Figure 6 User access permissions diagram

The main code in the login body Login.aspx is as follows:

  C # code   Private void loginbtn_click (object sender, system.eventargs e)        {      if (page.isvalid == true)       {           entity.user user=new user ();           string userId =  "";          string  isvalid= "";   //user's legal logos           //user identification           sqldatareader recs = user. Getuserlogin (UserName.Text.Trim (),      Entity.User.Encrypt (Password.Text.Trim ()));       if (RECs. Read ())           {             userid = recs["UserId"]. ToString ();       //Take to the user's legal flag &NBSP;&NBSP;&Nbsp;     isvalid=recs["state"]. ToString ();          }           RECs. Close ();          if (isvalid== "0")     //user not identified by system management , turn to access reject face       {Response.Redirect ("accessdenied.aspx");}       if ((userid != null)  &&  (userid !=  ""))        { session["UserID"] =userid;      entity.ckeckauthority  chkau=      new ckeckauthority ();     //user access check        if (!chkau. Chkpermission (int32.parse      (session["UserID"). ToString ())))       { //  direct to access reject polygon Response.Redirect ("accessdenied.aspx") if no permissions;}       else      {//user has access rights, create user name, password-verified ticket       Formsauthenticationticket ticket =       new formsauthenticationticket (           1,  // version  versions       UserName.Text.Trim ( ), //  User cookie name       datetime.now,      //  Release date       DateTime.Now.AddHours (1),//expiry date           false,        //cookie  persistence (false)       Password.Text.Trim ()   //   user Password      );          //   Encrypted notes       String cookiestr = formsauthentication.encrypt (ticket);      //  A string containing user name, password information into cookie      response.cookies["Userticket"]. value = cookiestr;      response.cookies["Userticket"]. path =  "/"; &Nbsp;     response.cookies["Userticket"]. Expires = datetime.now.addminutes (1);     //Jump to the main page that is dynamically generated by user rights Response.Redirect (" Default.aspx "); }     }      else      {   UserName.Text =  "";          password.text  =   ";          Message.Text = " The user name or password you entered is incorrect, please re-enter. ";     }     }     }        The main codes in    lefttree.aspx are as follows:      Private void page_load (object  sender, system.eventargs e)           {        ...            if (! Page.IsPostBack)           { //  InstancesA Tree object               tree tree = new  tree ();          //Dynamic Create Tree menu, parameter Moduletview to Treewview control object        tree. Bindtree (Moduletview,int32.parse (session["UserID"). ToString ()));         &nbsp ...}      }  

private void Loginbtn_click (object sender, System.EventArgs e) {if (Page.IsValid = = True) {Entity.user user=new User ();    String userId = "";  String Isvalid= ""; User's legal flag//user identification SqlDataReader RECs = username. Getuserlogin (UserName.Text.Trim (), Entity.User.Encrypt (Password.Text.Trim ())), if (RECs. Read ()) {UserID = recs["userid"].  ToString (); Take the user's legal flag isvalid=recs["state").    ToString (); } RECs.    Close (); if (isvalid== "0")//user is not managed by the system with OK, turn to access deny polygon {Response.Redirect ("accessdenied.aspx");} if (UserID = null) && (UserID = "")) {session["userid"] =userid; Entity.ckeckauthority chkau=new ckeckauthority ();//user access check if (!chkau. Chkpermission (Int32.Parse (session["UserID"). ToString ()))) {//If no permission is directed to the Access Denied Polygon Response.Redirect ("accessdenied.aspx");} else{//user has access rights, create user name, password Authentication ticket FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (1,//version versions username . Text.trim (),//user cookie name DateTime.Now,//Release date DateTime.Now.AddHours (1),//expiration date false,//cookiE persistence (False) Password.Text.Trim ()//user password); Encrypted ticket string cookiestr = Formsauthentication.encrypt (ticket);//The string containing the user name and password information is stored in cookieresponse.cookies[" Userticket "]. Value = cookiestr; response.cookies["Userticket"]. Path = "/"; response.cookies["Userticket"]. Expires = DateTime.Now.AddMinutes (1);//Jump to the main page Response.Redirect ("default.aspx") dynamically generated by user rights;    }}else{username.text = "";    Password.text = ""; Message.Text = "The user name or password you entered is incorrect, please re-enter."    ";}}} The main code in Lefttree.aspx is as follows: private void Page_Load (object sender, System.EventArgs e) {... if (!     Page.IsPostBack) {//Instantiate a tree object as the trees tree = new Tree (); Dynamically creates a tree menu with the parameter Moduletview Treewview control Object Tree.bindtree (Moduletview,int32.parse (session["UserID").    ToString ())); ...}}

In addition, in order to prevent illegal users from bypassing the login verification form directly and entering the access path directly in the URL, the user control in ASP. is used to encapsulate the ticket verification and role verification directly in the user control Checkuserauth.ascx. Adding a user control to each controlled page checkuserauth.ascx, if the illegal user directly to the denial of access page accessdenied.aspx, which makes the system more secure and reliable. This article does not repeat the configuration method for forms-based authentication in Web. config.

Operating effect:

The menu tree of roles for the score manager and system administrator is shown in Figure 7 and Figure 8.

Figure 7 Menu tree for the role of the score manager

Figure 8 The menu tree for the system Administrator role

Iv. Conclusion

In b/S mode, the security design of information system has a new demand, compared with the traditional C/s application, b/S application has higher requirements for security, not only to consider the security of data access, but also to consider the security of the network.

In this paper, with the idea of RBAC, using multi-layer architecture, using TreeView Control and ASP, we design a method of dynamically generating user's permission tree according to different user's role permissions, the method is efficient and safe, the user can only operate the module with permission, the module without permission is not visible to the user. Different users enter the interface different, improve the security and reliability of the system. Using this method, we can quickly construct a safe and efficient B/s management Information System.

I use Microsoft's Visual Studio.NET as the development platform, SQL Server as a database, press

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.