Knowledge points and specific implementation code of permissions in MVC

Source: Internet
Author: User

I. Knowledge Point

Permissions are a common knowledge point for Web pages. When using MVC for permission design, you must first understand the following knowledge:

In MVC, URL execution is based on the controller-> action-> View page, but we often need to process logic before the action specified by the function execution or after the action method, to process these logics, Asp. net MVC allows you to create an action filter. We all know that every [attribute] used on an action is a custom filter.

MVC provides four filter interfaces: iactionfilter, iauthorizationfilter, iexceptionfilter, iresultfilter,
These four filters are sufficient for the functions we want to implement. They also provide several

Which can be used: outputcacheattribute,
Handleerrorattribute and authorizeattribute. (Authorizeattribute and handleerrorattribute inherit from the filterattribute class)

Where:

IactionfilterTwo methods are provided:

Onactionexecuting Call before calling the Operation Method.Onactionexecuted Call after calling the operation method.

IresultfilterTwo methods are provided:Onresultexecuting


It is called before the operation result returned by the operation method is executed.Onresultexecuted

It is called after the operation result returned by the operation method is executed.

IauthorizationfilterIs a filter used for identity authentication. Only one void onauthorization (authorizationcontext filtercontext) method is provided.

IexceptionfilterIt is called when an exception occurs. It also provides only one void onexception (exceptioncontext filtercontext) method;

The execution sequence of the four interfaces is as follows: iauthorizationfilter-> iactionfilter-> iresultfilter-> iexceptionfilter

The actionexecutedcontext class contains a canceled attribute that allows you to cancel the current action]

Now let's take a look at the most used class.Actionfilterattribute:

HisThe inheritance hierarchy is

System. Object

System. Attribute
System. Web. MVC. filterattribute
System. Web. MVC. actionfilterattribute
System. Web. MVC. asynctimeoutattribute
System. Web. MVC. outputcacheattribute

 Public Abstract ClassActionfilterattribute: filterattribute, iactionfilter, iresultfilter { 
}
It inherits the three classes: filterattribute, iactionfilter, and iresultfilter. Generally, we need to process some functions before the Action Logic, such as permissions. Therefore, a filter will be customized, which inherits from
Actionfilterattribute, and then In actionfilterattribute, reload the functions inherited by the iactionfilter and iresultfilter interfaces.
VoidOnactionexecuting (actionexecutingcontext filtercontext)
VoidOnactionexecuted (actionexecutedcontext filtercontext)
VoidOnresultexecuting (resultexecutingcontext filtercontext)
VoidOnresultexecuted (resultexecutedcontext filtercontext)

WhereActionfilterattribute has two attributes, one being inheritedFilterattribute. The other inherits the attribute.

OrderObtains or sets the sequence of Operation filters.(Inherited from filterattribute .)

TypeidWhen implemented in a derived class, obtain the unique identifier of this attribute.(Inherited from attribute .)

For exampleCodeSection:

  [orderfilter (roleid  = "   2  "  , order  =  2  )] 
[userfilter (userid = " 3 " , order = 1 )]
Public actionresult test () {
return View ();
}

ProgramIn the execution order: userfilter-> orderfilter-> Test

Ii. Instances

 After learning about the above knowledge, let's take a look at the permission instance I designed: 
If you do not know the relationships between users, roles, groups, and permissions, we recommend that you first read the previous article "basic knowledge of permissions ".ArticleI turned it over and thought it was good because I didn't finish the project before.
Points are clear. Now After reading the article, I checked the check box to see that I performed the following operations based on the user, role, group, and permission relationships (if the check box below is incorrect, please correct me)
Assume that you have four function permissions: add, delete, publish, and modify. Designed in binary 01 format. 0 indicates that you do not have the permission for this function. 1 indicates that you have the permission,
That is to say, in order
Add Delete release Modification
1 1 1 if only the modified function is 0001,
If the add or delete function is 1100,

Convert binary to int: (1000 = Int 8) Delete: (0100 = int 4) Release: (0010 = int 2) function of modifying: (0001 = int count 1)
This can be understood as ----- permission
Each user has different functions (permissions) and can have multiple combinations, such as 1001 (ADD and modify permissions) 0011 (publish and modify permissions) 1111 (all permissions)
This can be understood as the ------- group.
For different users, I will change their permission combination function to the int value stored in the permission (INT) field of the User table. In this case: (ADD and modify permissions 1001 = int number 9)
(Publish and modify permissions 0011 = int count 3) (all permissions 1111 = int count 15)
This can be understood as -------- role
The user is the username in our own database.

Set User Permissions: you only need to add the int count with function permissions to the database;
View User Permissions: Resolve the int value of permission to the binary value first, and then look at the int value of 1 and the corresponding function value.
Implementation: when a user logs on, first check the int value of his permission (that is, the role) and resolve the role to the corresponding group, the Int value of each group is loaded into the roles of the user body, which is an array.
(Because there is one or more function permissions)
Then add the custom filter to each action that requires permission Filtering: In the overloaded onactionexecuting method, determine whether the current user's roles has this function permission. If so,
Otherwise, the page is displayed.

The following is the code.Actionfilterattribute class and overloadOnactionexecutingMethod:

 Public  Class  Rolefilter: actionfilterattribute {
Public String Checkrole { Get ; Set ;} // Function permission value to be passed in
Public Override Void Onactionexecuting (actionexecutingcontext filtercontext ){
If ( ! String . Isnullorempty (checkrole )){
If ( ! Filtercontext. httpcontext. User. Identity. isauthenticated ){ // Determine whether the user has logged on. If not, the logon page is displayed,
String Okurl = Filtercontext. httpcontext. Request. rawurl;
String Redirecturl = String . Format ( " ? Returnurl = {0} " , Okurl );
String Loginurl = Formsauthentication. loginurl + Redirecturl;
Filtercontext. Result = New Redirectresult (loginurl );
} Else { // Logged-on user
Bool Isauthorize = Filtercontext. httpcontext. User. isinrole (checkrole );
If ( ! Isauthorize) // Checks whether the user has the checkrole permission. If not, the permission error page is displayed.
Filtercontext. Result = New Redirecttorouteresult ( " Default " , New Routevaluedictionary ( New {Controller = " Account " , Action = " Authorizeerror " }));
}
} Else {
Throw New Invalidoperationexception ( " This user does not specify a role. Please contact the Administrator for a role. " );
}
}
}
 

When the program is started, read the permissions of the user role. To make the above comparison:
 Public  Mvcapplication (){
Authorizerequest + = New Eventhandler (mvcapplication_authorizerequest );
}

Void Mvcapplication_authorizerequest ( Object Sender, eventargs e ){
// Obtains the role of the current user.
If (Httpcontext. Current. User. Identity. isauthenticated ){
// The following method converts role (INT) to binary and calculates an array of int values for each permission.
VaR roles = Cmspermissioncontroller. instance. permissionidlist (httpcontext. Current. User. Identity. Name. Trim (). toarray < String > ();
Httpcontext. Current. User = New System. Security. Principal. genericprincipal (httpcontext. Current. User. Identity, roles );
}
}

 

 
The call process is as follows:

 //  You can also add [attribute] to the entire controller as needed]  
[Rolefilter (checkrole = " 2 " )]
Public Class Groupcontroller: controller {
Public Actionresult index (){
Return View ();
}

Public Actionresult create (){
Return View ();
}
}

// You can also add a specific action
[Rolefilter (checkrole = " 4 " )]
Public String Delete ( String Relapath ){
// To do...
}

 

 
The above code can basically be implemented. During the debugging process, a colleague asked me what to do if I want to check checkrole = "8" on Delete, I was a little confused... Not thinking
Too many, so I think the first checkrole is 4.The first checkrole is "8", but now it seems that there is no such situation, because the numbers I have defined, such as 4 and 8, are themselves fixed permissions, such
The permission numbers corresponding to add or delete a release change are 8, 4, 2, and 1. Therefore, if we want to grant the delete permission to 4,To check the added permission 8. The service logic does not exist! O (partition _ partition) O

I also saw an article about permissions: it is determined by the current URL and is worth learning for future research:
Http://www.cnblogs.com/legendxian/archive/2010/01/25/1655551.html













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.