ASP. NET MVC Permission control (c): Controller and Action level control

Source: Internet
Author: User
Tags httpcontext

Added on: ASP. NET MVC Permissions Control (II): Controller level control

Again in refactoring! This time the controller and action are validated.

Idea: The system has many feature sets, the feature set corresponds to many controllers and actions, and the roles are assigned many feature sets .


Start by building a basic data:

1. Feature Set initialization:

  <summary>///System module///</summary> public class Systemmodule {public Systemmodule ()        {this.id = Guid.NewGuid ();        Public Guid ID {get; set;}        public string Name {get; set;}        public string Description {get; set;}        Public Systemmodule Parent {get; set;}        Public list<systemmodulecontroller> systemmodulecontrollers {get; set;}            public static list<systemmodule> Init () {var m1 = new Systemmodule {Name = "resource Monitoring"};            var m2 = new Systemmodule {Name = "planning Management"};            var C1 = new Systemmodulecontroller {controllername = "planmanagement", ActionName = "Search"};            var C2 = new Systemmodulecontroller {controllername = "planmanagement", ActionName = "Add"};            var C3 = New Systemmodulecontroller {controllername = "planmanagement", ActionName = "Edit"}; var C4 = new Systemmodulecontroller {controllername = "PlaNmanagement ", ActionName =" Delete "};            var c5 = new Systemmodulecontroller {controllername = "planmanagement", ActionName = "Approval"}; var M21 = new Systemmodule {Name = "Planning information query", Parent = m2, systemmodulecontrollers = new List<systemmodulecontroller&gt ;            {C1}}; var M22 = new Systemmodule {Name = "Planning information management", Parent = m2, systemmodulecontrollers = new List<systemmodulecontroller&gt ;            {C2, C3, C4}}; var M23 = new Systemmodule {Name = "Planning for secondary approval", Parent = m2, systemmodulecontrollers = new List<systemmodulecontroller&gt ;            {c5}};        return new List<systemmodule> {m1, M2, M12, M21, M22, M23}; }    }

2. Role initialization:

    <summary>    ///roles///</summary> public class SystemRole {public        systemrole ()        {            this.id = Guid.NewGuid ();        }        Public Guid ID {get; set;}        public string Name {get; set;}        public string Description {get; set;}        Public list<systemmodule> systemmodules {get; set;}        public static SystemRole Init (string[] roles)        {            var modules = Systemmodule.init ();            var systemmodules = roles. Select (r = modules. FirstOrDefault (m = M.name = = r)). ToList ();            var role = new SystemRole {Name = "Default Role", Systemmodules = systemmodules};            return role;        }    }

3. Read all Controller and action of the system

 <summary>///Read all Controller and action of the System////</summary> public class Systemmodulecontroller {        Public Systemmodulecontroller () {this.id = Guid.NewGuid ();        Public Guid ID {get; set;}        public string ModuleName {get; set;}        public string Controllername {get; set;}        public string ActionName {get; set;}        public string Description {get; set;}        Public list<systemmodulecontroller> systemmoduleactions {get; set;} public static list<systemmodulecontroller> Getsystemmodulecontroller () {var Systemmodulecontrolle            rs = new list<systemmodulecontroller> (); Read controller var types = assembly.load ("Prmms" in the project. Authorization "). GetTypes ().            Where (b = b.basetype = null && B.basetype.name = = "Basecontroller"); foreach (var type in types) {//Tag controller var modules that requires permission validation= Type.                GetCustomAttributes (typeof (Moduleauthorizationattribute), true); if (modules. Length = = 1) {//controller name var controllername = type.                    Name.replace ("Controller", "" "); Controller describes var description = string.                    Empty; var attrs = type.                    GetCustomAttributes (typeof (System.ComponentModel.DescriptionAttribute), true); if (attrs. Length > 0) {description = (Attrs[0] as System.ComponentModel.DescriptionAtt Ribute).                    Description; }//Get action var under controller systemmodulecontrolleraction = new List<systemmodul                    Econtroller> (); var actions = type. GetMethods ().                    Where (A = a.returntype! = NULL && A.returntype.name = = "ActionResult");                    foreach (var action in actions) {    Action name var actionname = action.                        Name; The action describes var desc = string.                        Empty; var act = action.                        GetCustomAttributes (typeof (System.ComponentModel.DescriptionAttribute), true); if (act. Length > 0) {desc = (Act[0] as System.ComponentModel.DescriptionAttr Ibute).                        Description;                                                             } systemmodulecontrolleraction.add (New Systemmodulecontroller                                                                 {controllername = Controllername,                                                                 ActionName = ActionName,                    Description = desc}); } var SystemmodUle = new Systemmodulecontroller {controllername = Controllername,                    Description = Description, systemmoduleactions = systemmodulecontrolleraction                    };                Systemmodulecontrollers.add (Systemmodule);        }} return systemmodulecontrollers; }    }

  

After the system logs on, initialize the permissions and save the cache.

        [HttpPost]        [Validateantiforgerytoken]        Public ActionResult Login (Loginmodel model, string returnUrl)        {            var userName = model. UserName;            FormsAuthenticationTicket AuthTicket = new FormsAuthenticationTicket (            1,            userName,            DateTime.Now,            DateTime.Now.AddMinutes (),            false,            model. Roles.aggregate ((i, j) = + i + "," + j)            );            String encryptedticket = Formsauthentication.encrypt (AuthTicket);            var Authcookie = new HttpCookie (Formsauthentication.formscookiename, encryptedticket);            SYSTEM.WEB.HTTPCONTEXT.CURRENT.RESPONSE.COOKIES.ADD (Authcookie);            Initialize Permissions            var systemrole = systemrole.init (model. Roles);            Cache Permissions            Accounthelper.addcache (systemrole.systemmodules);            Return redirecttoaction ("Index", "Home");        

Accounthelper:

    public class Accounthelper {Private Const string cachename = "Systemmodules";  <summary>///For user information//</summary>//<returns></returns> public Static FormsAuthenticationTicket Getcookieuser () {HttpCookie Authcookie = HttpContext.Current.Request.            Cookies[formsauthentication.formscookiename];            if (Authcookie = = NULL | | authcookie.value = = "") {return null;            } try {return formsauthentication.decrypt (authcookie.value);            } catch (Exception ex) {return null; }}///<summary>//Add cache///</summary>//<param name= "Systemmodules "></param> public static void Addcache (List<systemmodule> systemmodules) {Httpcon Text.        Current.cache[cachename] = systemmodules;  }      <summary>//Read cache///</summary>//<returns></returns> PU            Blic static list<systemmodule> GetCache () {if (httpcontext.current.cache[cachename] = = null)                {//re-build permissions var user = Getcookieuser (); var roles = user.                Userdata.split (new[] {', '}); Httpcontext.current.cache[cachename] = systemrole.init (roles).            Systemmodules;        } return (list<systemmodule>) httpcontext.current.cache[cachename]; }///<summary>//Verify Controller and action///</summary>//<param name= "control Lername "></param>//<param name=" ActionName "></param>//<returns></returns > public static bool Validatepermission (string controllername, String actionname) {var system            Modules = GetCache (); foreach (Var systemmoduLe in Systemmodules) {if (systemmodule! = null && systemmodule.systemmodulecontrollers                    ! = null) {foreach (var controller in Systemmodule.systemmodulecontrollers) {if (Controller. Controllername = = Controllername && controller.                    ActionName = = ActionName) return true;        }}} return false; }    }

  

Also add intercept tags to the business controller

    [Loginallow]    [Permissionfilter]    public class Basecontroller:controller    {    }    [Description ("Planning Management Controller")]    [moduleauthorization]    public class Planmanagementcontroller:basecontroller    {        [Description ("Home page")] public        ActionResult Index (        {            return View ();        }        [Description ("Query")]        Public ActionResult Search ()        {            return View ();        }        [Description ("Add")]        Public ActionResult Add ()        {            return View ();        }        [Description ("edit")]        Public ActionResult Edit ()        {            return View ();        }        [Description ("delete")]        Public ActionResult Delete ()        {            return View ();        }        [Description ("Approval")]        Public ActionResult Approval ()        {            return View ();        }    }

  

Interceptor: Permissionfilterattribute

  [AttributeUsage (AttributeTargets.Class |        AttributeTargets.Method, AllowMultiple = False)] public class Permissionfilterattribute:actionfilterattribute {        Called by the ASP. OnActionExecuted after executing the action method.        Called by the ASP. OnActionExecuting before executing the action method.        Called by the ASP. Onresultexecuted after executing the result of the operation.        Onresultexecuting is called by the ASP. NET before executing the result of the operation.        <summary>///is called by the ASP framework before executing the action method. </summary>//<param name= "Filtercontext" ></param> public override void Onactionexecu            Ting (ActionExecutingContext filtercontext) {//fcinfo = new Filtercontextinfo (filtercontext); Process if (!this) according to the validation judgment. Authorizecore (Filtercontext)) {FilterContext.RequestContext.HttpContext.Response.Redirect ("~/ac            Count/login "); }}///<summary>///authority Judgment business logic////</summary>//<param NamE= "Filtercontext" ></param>///<returns></returns> protected virtual bool Authorizecore        (ActionExecutingContext Filtercontext)            {object[] filter; Verifies whether the current action is an anonymous access action filter = FilterContext.Controller.GetType ().            GetCustomAttributes (typeof (Anonymousattribute), true); if (filter.            Length = = 1) {return true; }//Verifies whether the current action is a permission Control page action filter = FilterContext.Controller.GetType ().            GetCustomAttributes (typeof (Moduleauthorizationattribute), true); if (filter. Length = = 1) {//Get controllername name var controllername = Filtercontext.routedat a.values["Controller"].                ToString (); Get the action name var actionname = filtercontext.routedata.values["Action"].                ToString ();            Return Accounthelper.validatepermission (Controllername, actionname); }//TestThe current action is the login user Action filter = FilterContext.Controller.GetType ().            GetCustomAttributes (typeof (Loginallowattribute), true); if (filter.            Length = = 1) {return HttpContext.Current.User.Identity.IsAuthenticated; } throw new Exception ("User authentication failed!        "); }    }

  

Code Download: PRMMS.Authorization.zip

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.