In the previous section, you mentioned that you can use Authorizeattribute for Rights management:
[Authorize] Public ActionResult testauthorize () { return View (); } [Authorize (users= "Test1,test2")] Public ActionResult testauthorize () { return View (); } [Authorize (roles= "Admin")] Public ActionResult testauthorize () { return View (); }
However, usually, the permissions of the site is not fixed, when the new role or role changes, can only modify the corresponding characteristics of each action, when the project is large workload imaginable. Fortunately, we can rewrite Authorizeattribute to achieve custom rights management. Create a new Customauthorizeattribute class that inherits this class from Authorizeattribute. Open Authorizeattribute See the method description below, we only need to rewrite Authorizecore and onauthorization to achieve our goal.
Summary://When overridden, provides a entry point for custom authorization checks. Parameters://HttpContext://The HTTP context, which encapsulates all http-specific inf Ormation on//an individual HTTP request. Returns://True if the user is authorized; otherwise, false. Exceptions://System.ArgumentNullException://The HttpContext parameter is null. Protected virtual bool Authorizecore (httpcontextbase HttpContext);///Summary://Called when a proc ESS requests authorization. Parameters://Filtercontext://The filter context, which encapsulates information for u Sing System.Web.Mvc.AuthorizeAttribute. Exceptions://System.ArgumentNullException://The Filtercontext parameter is null. public virtual void Onauthorization (AuthorIzationcontext filtercontext);
Overloading the Authorizecore method in Customauthorizeattribute, its processing logic is as follows: first determine whether the current account is authenticated, if not, then return false, and then get the current account type, and compare with the given type, Returns True if the type is the same, otherwise false. In the general Web site, permission management uses the permission tree and then saves the permissions of the role to the database or file, in this case we use an XML file to save the role of each action, so that when the user requests the action, the XML file gets the corresponding permission for the action. Then detect if the account has appropriate permissions. The code for the Customauthorizeattribute class is as follows:
public class CustomAuthorizeAttribute:System.Web.Mvc.AuthorizeAttribute {public new string[] Roles {get; set ; } protected override bool Authorizecore (HttpContextBase HttpContext) {if (HttpContext = = null) { throw new ArgumentNullException ("HttpContext"); } if (!httpcontext.user.identity.isauthenticated) {return false; } if (Roles = = null) {return true; } if (roles.length = = 0) {return true; } if (Roles.any (HttpContext.User.IsInRole)) {return true; } return false; } public override void Onauthorization (System.Web.Mvc.AuthorizationContext filtercontext) {Strin G controllername = FilterContext.ActionDescriptor.ControllerDescriptor.ControllerName; String actionname = FilterContext.ActionDescriptor.ActIonname; String roles = Getroles.getactionroles (ActionName, controllername); if (!string. Isnullorwhitespace (roles)) {this. Roles = Roles. Split (new string[] {","}, Stringsplitoptions.removeemptyentries); } base. Onauthorization (Filtercontext); } }
When the user requests an action, the Onauthorization method is called, and the method is Getroles.getactionroles (ActionName, controllername); Based on the Controller and action to find the type of role the current action needs to have, after obtaining the action's roles, authorizecore the user's role in the Roles.any ( HttpContext.User.IsInRole), returns False if there is no corresponding permission, and the program automatically jumps to the login page.
GetRoles is the XML parsing class with the following code:
public class GetRoles {public static string Getactionroles (string action, string controller) { XElement RootElement = Xelement.load (HttpContext.Current.Server.MapPath ("/") + "Actionroles.xml"); XElement controllerelement = Findelementbyattribute (rootelement, "Controller", controller); if (controllerelement! = null) { XElement actionelement = Findelementbyattribute (controllerelement, "Action", Action); if (actionelement! = null) { return actionelement.value; } } Return ""; } public static XElement Findelementbyattribute (XElement xelement,string tagName, string attribute) { return Xelement.elements (TagName). FirstOrDefault (x = X.attribute ("name"). Value.equals (Attribute,stringcomparison.ordinalignorecase)); } }
The appropriate permissions XML file:
<?xml version= "1.0" encoding= "Utf-8"?><roles> <controller name= "Home" > <action name= " Index "></Action> <action name=" about ">Manager,Admin</Action> <action name=" Contact ">Admin</Action> </Controller></Roles>
When requirements change, only the XML file needs to be modified to
When using, you only need to register the filter in the Filterconfig
Filters. ADD (New Customauthorizeattribute ());
Of course, this is just a simple example, the actual application will be much more complex, but also possible to achieve the imminent membershipprovider and RoleProvider
MVC Custom Authorizeattribute for Rights management