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

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


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

Author: anon

First, the introduction

With the introduction of the. NET and Java EE Development platform, the traditional software development mode has changed to the B/S mode, which has put forward a higher requirement for the security of the system, because of the particularity of the HTTP protocol and the browser, it may cause the leakage of information and even make the illegal users modify data. and the establishment, distribution and management of permissions is an essential function of any system. How to design and implement its functions, there are a variety of programs, the traditional access control method DAC (discretionary access controls, autonomous access control model), MAC (Mandatory access controls, Mandatory access control model) is difficult to meet complex enterprise environment requirements. In this paper, we use the basic idea of role-based access control (RBAC and role Based access controls), and make use of the Web control TreeView and ASP.net technology, and design a b/s mode, according to different users, different role permissions, A concrete implementation method of dynamically generating User menu tree.

This article will introduce the basic idea of RBAC first, on this basis, give the concrete realization method in asp.net.

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



Fig. 1 The basic idea of RBAC

In RBAC, the license permissions (privilege) is the power to allow execution of 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 right and the role, and the role to the user, which realizes the logical separation of the user and the access rights.

The authorization of RBAC to access authority is managed by the system administrator, the system administrator defines different roles according to different positions in the organization, and the user is given 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 logic separation of user and access rights, it facilitates the complexity of privilege management greatly. The user can be associated with the role based on the user's actual job position, while defining the role, increasing the user's ease of action in the deletion role, and, on the other hand, changing the privileges of the role to achieve a large volume of user rights updates. In practice, because the change between roles/permissions is much slower than the change between user/role, when a user's position changes, as long as the user's current role is removed, to join the role of representing the new position. Therefore, the advantages of RBAC are obvious, more in line with the application characteristics of enterprises.

Third, User rights menu tree

Dynamic implementation of user rights with TreeView control the basic idea of the menu tree is: According to the basic principle of Role access control (RBAC), assigning different roles to users, each role corresponding to some permissions, and then according to the user ID to obtain the corresponding role set, by the role set to get the corresponding set of permissions, A permission tree that consists of a page (module) that the user's corresponding role can access is dynamically generated by the permission set using the Treewiew control. In this way, the user does not have access to the page in the Permission menu tree will not appear, different users enter the interface is different, realize the unified management of user rights.

The following from the functional module design, database design, architecture design and other aspects to explain its implementation process.

1. Functional Module Division

 

Figure 2 User Rights management function module diagram

The user Rights management system functions as shown in Figure 2, where the main module features are described as follows:

User Management module is divided into: delete users, browse users and Role assignment three modules, mainly responsible for the deletion of various users, legality verification and assign roles to users. User Management module does not increase the function of the user's child module, mainly by the user registration module to achieve.

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

2. Database Design

In order to improve the efficiency of system management and data access when implementing RBAC to generate User Rights menu tree, the user table (shown in table 1), the Role table (shown in table 2), the User Role table (shown in table 3), the Role permission table (shown in table 4), and the menu tree structure table (shown in table 5) are designed in the database for 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 trees

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 corresponds to a menu, the parent-child relationship between the menus directly reflects the parent-child relationship between the modules, and a table tree is used in the database to store the structure.

The 5-table relationship is shown in Figure 3.

Figure 3 Diagram of 5 tables

3. System Architecture Design

b/S mode, three-layer structure: presentation layer, logic layer and data layer. For programming convenience, the data layer is divided into solid layer and data access layer, and all the code that opens, closes the database and invokes the stored procedure is sealed in the data access class SQLHelper.cs. The practical application of the four-tier structure, the system architecture design as shown in Figure 4.

Figure 4 User Rights Management architecture diagram

NOTE: the arrow in Figure 4 is the calling relationship.

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

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

(1) User class:

Getuserlogin (String susername,string spassword): User logon authentication.

Getrolebyuser (int Nuserid): Returns all of the user's role set by the user ID.

Adduserrole (int nuserid,int nroleid):

Assign a role to a user.

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

(2) Role class Roleentity:

Addrolemodule (int ntreeid,int nroleid): Assigning Permissions to roles.

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

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

(3) Permission Tree trees:

Bindtree (TreeView treeview,int UserID): Spanning Tree directory.

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

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

(4) User Rights check class Ckeckauthority:

chkpermission (int UserID): Checks to see if the user has access rights.

IsInRole (int Roleid): Checks to see if a role exists.

4. Concrete implementation

In a tree structure, the role of the authorization to take a simple way, each authorization, its 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 must be installed in the ASP.net development environment (available for free download to Microsoft's website), and after installation, reference Microsoft.Web.UI.WebControls.dll in the development environment, This will show IE Web controls such as Mutipage, TabStrip, Toobar, and TreeView in the toolbox of the development environment.

Adding the IE Web control treeview to a Web page is divided into 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 where you want the TreeView to appear in your Web page:

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

...

</iewc:treeview>

Readers can refer to the corresponding books for the use of the TreeView control.

The overall architecture page includes the user login (longin.aspx) and the main interface (Default.aspx) two parts.

The main interface is divided into three parts: the upper section is the title bar (head.aspx), the left part is the menu directory tree (lefttree.aspx), and the right part 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 is validated by Windows and is responsible for providing user authentication. Then according to the user's role in the system, take out the user's corresponding permission set, dynamically generate the user corresponding to the system's Operation rights tree (see Figure 6).



Figure 6 User access rights schematic

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 logo           //user identification           sqldatareader recs = user. Getuserlogin (UserName.Text.Trim (),      Entity.User.Encrypt (Password.Text.Trim ());       if (RECs. Read ())           {             userid = recs["UserId"]. ToString ();       //access to the user's legal flag &NBSP;&NBSP;&Nbsp;     isvalid=recs["state"]. ToString ();          }           RECs. Close ();          if (isvalid== "0")     //user not identified by system administration , turn to access reject face       {Response.Redirect ("accessdenied.aspx");}       if ((userid != null)  &&  (userid !=  "")        { session["UserID"] =userid;      entity.ckeckauthority  chkau=      new ckeckauthority ();     //user access permission test        if (!chkau. Chkpermission (int32.parse      (session["UserID"). ToString ()))       { //  Response.Redirect ("accessdenied.aspx") if no permissions are directed to access denied surfaces;       else      {//user has access rights, create user name, password verified Bill       Formsauthenticationticket ticket =       new formsauthenticationticket (           1,  // version  version       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      );          //   Encryption Bill       String cookiestr = formsauthentication.encrypt (ticket);      //  The string containing the user name and password information into cookie      response.cookies["Userticket". value = cookiestr;      response.cookies["Userticket"]. path =  "/"; &Nbsp;     response.cookies["Userticket"]. Expires = datetime.now.addminutes (1);     //Jump to a dynamically generated home page with user rights Response.Redirect (" Default.aspx "); }     }      else      {   UserName.Text =  "";          password.text  =   "";          Message.Text =  "The username or password you entered is incorrect, please re-enter it. ";     }     }     }        The main code in    lefttree.aspx is as follows:      Private void page_load (object  sender, system.eventargs e)           {        ...            if (! Page.IsPostBack)           { //  ExampleA Tree object               tree tree = new  tree ();          //Dynamically 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 logo//user identity 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 determined 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 permission check if (!chkau. Chkpermission (Int32.Parse (session["UserID"). ToString ())) {//If no permissions are directed to the Access Denied face Response.Redirect ("accessdenied.aspx");} else{//users have access to create user names, password-validated bills FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (1,//version 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);//A string containing the user name and password information is stored cookieresponse.cookies[" Userticket "]. Value = cookiestr; response.cookies["Userticket"]. Path = "/"; response.cookies["Userticket"]. Expires = DateTime.Now.AddMinutes (1);//jump to a dynamically generated home page with user rights Response.Redirect ("default.aspx");    }}else{username.text = "";    Password.text = ""; Message.Text = "You entered the user name or password 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 trees = new (); Dynamically create a tree menu with parameters Moduletview Treewview Control Object Tree.bindtree (Moduletview,int32.parse (session["UserID").    ToString ())); ...}}

In addition, in order to prevent illegal users bypassing the login authentication form directly and accessing the access path directly in the Web address, the user control in asp.net is used to encapsulate the ticket verification and role verification directly in the user control Checkuserauth.ascx. Adding a user control Checkuserauth.ascx to each controlled page makes the system more secure and reliable if you turn to an illegal user to deny access to the page accessdenied.aspx. This article does not dwell on the forms-verified configuration approach in Web.config.

Operation Effect:

The roles are the performance manager and the System Administrator menu tree as shown in Figure 7 and Figure 8.

Figure 7 The role of the performance manager's menu tree

Figure 8 The role is the system administrator's menu tree

Four, the conclusion

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

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

The author uses Microsoft's Visual Studio.NET as a development platform, SQL Server as a database,

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.