Use of authority management tools
There is a function in the development of today's commercial software. This is the authority tool. If you want everyone to be too strange, you should use permissions to many software around us, such as the most common The Windows operating system uses permissions, but in the actual development process, permissions are quite troublesome. Everyone is looking for a simple permission management method. At this time we discovered this component, this is a very good functional authority management component, which allows us to control the power of the software very simple.
Use cg.security you can add delete permissions, roles, and permissions. You can give users a role through most permissions management or give privileges directly.
Ok, short introduction to the functionality of cg.security, will explain the usage of this component. Please download the component on http://www.codeproject.com/csharp/codeproject.com before explaining.
The following explanation will be divided into two parts:
The first part will explain the usage of some method properties common in this class library. The second part passes a small Demo, giving everyone a sense of understanding, so that everyone understands how to use cg.security in the actual development.
First, the common method of class library
Six classes are used in this component to achieve user management, authority management, and role management.
UserManager: This class provides methods for adding, deleting, and looking for users.
RoleManager: This class provides a way to add, delete, and find roles.
RightManager: This class provides a way to add, delete, and modify permissions.
UserrightManager: This class's role is to use the user and permission association, and also provides, delete, check, and use this class, you can directly assign permissions for a user.
UserRoleManager: This class is similar to the UserrightManager above, and it provides a similar function, which is related to the user and role.
ROLERIGHTMANAGER This class provides roles and permissions.
After the above six classes are introduced, the following will be introduced to a class that will be used in actual development.
SecurityManager.cs class, which provides a function of logging in verification and obtaining the user permission list (EffectiveRights). Using this class We can determine the legality of the user and get the list of permissions from the current user.
The above describes the functions of several common class in the permission management component. Let everyone have a comprehensive understanding of the authority management components. The following part I will make a small demo step by step to make you a sense of sensibility to this component. OK, even enter the next link.
Second, do a small Demo to demonstrate how to use this permission tool
First, do a small demo to demonstrate how to use this permission tool
1. We will implement data permissions and functional permissions in this Demo. First we have to download the component from the Internet, which can be found from http://www.codeProject.com/csharp/codecurity.asp, and find the cg.security.dll file in the bin / release directory after downloading.
2. Create a solution CG.SecurityTest.
3. Then add a MainMenu on Form1, then add 4 sub-items above, name Mltest1, Mltest2, Mltest3, Mltest4, and then set their Visible to false.
4. When we add a menu, we have to add a DataGrid and 3 buttons.
Change the DataGrid's name to DGView; 3 buttons are named BTNALLUSER, BTNTEST1 and BTNVIEW, respectively.
Then set the enabled attribute of btntest1 to false.
5. What is added above is our main interface, let's add a secondary interface to enter information such as username password, add a new Windows Form on the project, and then name FormValue. When the form is newly entered, two TextBox is newly built on the form. TEXTBOX is named TXTNAME, TXTPWD, but BTNOK, BTNCANCEL. And set BTNOK's DialogResult property to OK, the DialogResult property of BTncel is set to Cancel. After the form is set, we add two properties in your code.
Public String Uid
{
Get {return txtname.text.trim ();
}
Public String PWD
{
Get {return txtpwd.text.trim ();
}
OK After the above three steps, our interface work is completed. Here we will begin their specific features..
6. First reference cg.security.dll this component in the project species. Import CG.Security and cg.security.principal on Form1. 2 namespaces.
Using cg.security;
Using cg.security.principal;
:) This step is essential.
7. After adding the reference. We also have something to prepare - configuration files, then first we add a new app.config, then copy the following code to app.config:
XML Version = "1.0" encoding = "UTF-8"?>
sectiongroup>
configsections>
Sectionname = "access" Targetassembly = "cg.security" Targetnamespace = "cg.security.data.access" CONNECTIONSTRING = "provider = microsoft.jet.Oledb.4.0; data source = f: /tempfile/cgsecuritydemo/bin/debug/security.mdb" /> installedassembly> runtimesetup> configure> The above profile can see some information to connect to the database. He uses the cg.setting.data.configuration.datasettingshandler class to read database information, we can clearly see the connection string in the configuration file. This profile uses OLEDB to connect to the Access database in the specified directory. It should be placed in the F drive, here everyone should come according to the actual location of your own data. When all the configurations have been completed, we have started to implement specific code. 8. The first step in entering the application is definitely to verify the legality of the current user. OK then we first start from the form of the form: First we have to define a global String array STR. Then add the following code in the FormLoad event. / / Installation Login Form FormValue FV = New FormValue (); IF (fv.Showdialog (this)! = DialogResult.ok) { THIS.CLOSE (); Return; } / / Verify the user's ID and password IF (! SecurityManager.Authenticate (fv.uid, fv.pwd)) { Messagebox.show ("" "User Name or Password is incorrect!"); THIS.CLOSE (); Return; } System.appdomain.currentdomain.setthreadprincipal New Customprincipal (New CustomIdentity (Fv.UID)) ); OLEDBDATAREADER DATAREAD = (OLEDBDATAREADER) UserManager.findbyUserName (fv.uid); DataRead.Read (); Str = securityManager.effectiverights (DataRead.Getint32 (0)); // Cycle each permission FOREACH (String Strsingle in Str) { Switch (strsingle) { Case "Test 1": Mitest1.visible = true; BTNTEST1.ENABLED = True; Break; Case "Test 2": mitest2.visible = true; Break; Case "Test 3": mitest3.visible = true; Break; Case "Test 4": Mitest4.visible = true; Break; } } Everyone sees the above code is a typical application of permission management. I will explain this code step by step. First we can see such a code FormValue FV = New FormValue (); IF (fv.Showdialog (this)! = DialogResult.ok) { THIS.CLOSE (); Return; } This code is first instantially a form that enters the username password, and then determines whether the user clicks OK, exit the program if the user does not click OK. IF (! SecurityManager.Authenticate (fv.uid, fv.pwd)) { Messagebox.show ("" "User Name or Password is incorrect!"); THIS.CLOSE (); Return; } This code is the essence, the SecurityManager class is a verification class where we call its Authenticate method, which accepts two parameters, usernames, and passwords. And return a BOOL value, thereby we can determine whether the user's username is correct. System.appdomain.currentdomain.setthreadprincipal New Customprincipal (New CustomIdentity (Fv.UID)) ); The sentence means that a user is bound to the primary object of the thread, where we pass the currently logged in user ID, then you can know the currently logged in the program. OLEDBDATAREADER DATAREAD = (OLEDBDATAREADER) UserManager.findbyUserName (fv.uid); DataRead.Read (); Str = securityManager.effectiverights (DataRead.Getint32 (0)); The above code is how to use the right. First we call UserManager.FindBYUSERNAME methods to get a DataReader object (this method is to find information by the username) and then read the DataReader object to get the ID of the current user. Finally, call the SecurityManager.effectiverights method List all the privileges owned by the user in a string array. // Cycle each permission FOREACH (String Strsingle in Str) { Switch (strsingle) { Case "Test 1": Mitest1.visible = true; BTNTEST1.ENABLED = True; Break; Case "Test 2": mitest2.visible = true; Break; Case "Test 3": mitest3.visible = true; Break; Case "Test 4": Mitest4.visible = true; Break; } } Here we have just got the permissions array, then judge whether the user has a function permission, such as Test 1 permissions, let him use the TEST1 menu and btntest1 buttons. At this time, you can compile the program, what is the difference between the Admin User into the system and take the user? Oh, everyone can see that the menu Test1 and Test4 are gone when using USER, and there is a btntest1 button to become gray. 9. Here, we tell how to use functional permissions, next, I will use the sample program of a master-slave table to explain how to use data permissions, our final effect is the user who has TEST4 privileges can be seen. The main table sees from the table, and vice versa, only the primary table can be seen. Ok, first we add a Orders.mdb database in a bin / debug directory, then build 2 tables orders and OrderList, respectively. The ORDERS table field is as follows Ordered automatic number ORDERTYPE text (order category) ORDERTIMER Date Time (Time) The ORDERLIST table field is as follows ORDERLISTID Auto Number ORDERID number (ID) PRODNAME text (product name) Count numbers (quantity) When you create the above table format, you will associate the ORDERID value of the Orders and OrderList tables later. After the above steps are finished, add several data to the database. The OK database is ready, we should also see how to achieve it, add the following code in the click event of BTNView: OLEDBCONNECTION CON = New OLEDBConnection (@ "provider = microsoft.jet.Oledb.4.0; data source = orderrs.mdb"); C.Open (); OLEDBDataAdapter Da = New OLEDBDataAdapter ("Select * from Orders", CON); DataSet DS = New Dataset (); Da.fill (DS, " Main "); DGView.DataSource = DS.TABLES [0]; DGView.tables.clear (); DataGridtableStyle DTS = New DataGridTableLe (); DataGridTextBoxColumn DCStype = New DataGridTextBoxColumn (); DataGridTextBoxColumn DCSName = New DataGridTextBoxColumn (); DCStype.mappingname = "Ordertype"; DCStype.Headertext = "Type"; Dcsname.mappingname = "ORDERTIMER"; DCSName.Headertext = "Time"; DTS.GridColumnStyles.Add (DCStype); DTS.GridColumnStyles.Add (dcsname); DTS.MAppingName = DS.TABLES [0] .tablename; DGView.TablesTyles.Add (DTS); FOREACH (String Stra in Str) { // If the user can see the content from the table when the user has this permission IF (stra == "TEST 4") { OLEDBDATADAPTER DALIST = New OLEDBDATAADAPTER ("Select * from ORDERLIST WHERE ORDERID IN (SELECT Orderid from Orders)", Con); Dalist.Fill (DS, "List"); DS.RELATIONS.ADD (DS.Tables [0] .Columns ["OrderID"], DS.Tables [1] .COLUMNS ["OrderID"]); DataGridTableStyle DTL = New DataGridtableStyle (); DataGridTextBoxColumn DclName = New DataGridTextBoxColumn (); DataGridTextBoxColumn Dclcount = New DataGridTextBoxColumn (); DclName.mappingName = "prodname"; DclName.Headertext = "Product Name"; Dclcount.mappingname = "count"; dclcount.Headertext = "quantity"; DTL.GridColumnStyles.Add (DclName); DTL.GridColumnStyles.Add (dclcount); DTL.MAppingName = DS.TABLES [1] .tablename; DGView.TablesTyles.Add (DTL); Break; } } The above code is very simple, all common database operations, I want to explain the convenient loop. FOREACH (String Stra in Str) { // If the user can see the content from the table when the user has this permission IF (stra == "TEST 4") { OLEDBDATADAPTER DALIST = New OLEDBDATAADAPTER ("Select * from ORDERLIST WHERE ORDERID IN (SELECT Orderid from Orders)", Con); Dalist.Fill (DS, "List"); DS.RELATIONS.ADD (DS.Tables [0] .Columns ["OrderID"], DS.Tables [1] .COLUMNS ["OrderID"]); ...... } The above code is also the permissions to traverse the current user. Then determine whether there is Test 4 permissions. If you have test4 permissions, check out the records from the table and associate with the primary table. If there is no Test 4 permission, you will not query the slave table. Last 1 minute: After the above steps, a permission management Demo is completed, you can use admin and user two users to see, you can clearly see the admin to operate all menus and view the data from the primary slave table, but the user user only Can operate the TEST2 and TEST3 menus and can only see the data of the primary table. Review the above document, I first introduce the common class and common methods of the component, in the second part we have implemented how to use functional permissions and data privileges in the program through an example. Such a complete permission management Demo is complete, of course, you can also increase or delete some unwanted features based on your own needs, and have not mentioned the Demo comes with this component, should bring it to it. Demo is used as authorization tools and is very simple to operate. I am not tired here.