ASP. NET MVC permission control (ii): Controller level control

Source: Internet
Author: User
Tags httpcontext

continued: ASP. NET MVC Permissions control (i): simple implementation using authorize Roles

This example uses ActionFilterAttribute for permission interception because there are significant limitations to tagging role names directly on the controller.

First create a class three tag:

1. Anonymous access token (anonymousattribute)
2. Login user access tag (loginallowviewattribute)
3. Authorization authentication access token (Permissionpageattribute)

One of the most important permissions interception: Authorizefilter, including three-step verification:

1. is anonymous access, if anonymous access is passed directly;
2. Whether to verify the permission, by querying the cookie saved at login;
3. Whether it is logged in, if the login directly through;

    <summary>//Rights intercept///</summary> [AttributeUsage (AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = False)] public class Authorizefilter:actionfilterattribute {///        Lt;summary>///is called by the ASP framework before executing the action method. </summary>//<param name= "Filtercontext" ></param> public override void Onactionexecu Ting (ActionExecutingContext filtercontext) {//based on the validation judgment to process if (!this. Authorizecore (Filtercontext)) {FilterContext.RequestContext.HttpContext.Response.Redirect ("~/ac            Count/login "); }}///<summary>///authority Judgment business logic///</summary>//<param name= "Filterc Ontext "></param>//<param name=" Isviewpage "> whether it is a page </param>//<returns></ret  urns> 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 (Permissionpageattribute), 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 ();                var validateauthorize = new Validateauthorize ();            Return Validateauthorize.validate (controllername); }//Verifies whether the current action is the logged on user action filter = FilterContext.Controller.GetType (). GetCustomAttributes (typeof (Loginallowviewattribute), true); if (filter.            Length = = 1) {return HttpContext.Current.User.Identity.IsAuthenticated; } throw new Exception ("User validation Error!        "); }    }

  

Save user information after the user logs on.

  [HttpPost]  [Validateantiforgerytoken] public actionresult Login (Loginmodel model, string returnUrl) {string            UserData = ""; var userName = model.            UserName;            if (UserName = = "Admin") {UserData = "Log";            } else if (UserName = = "in") {UserData = "Infrastructure";            } else if (UserName = = "fl") {UserData = "filelibrary";            } FormsAuthenticationTicket AuthTicket = new FormsAuthenticationTicket (1, UserName,            DateTime.Now, DateTime.Now.AddMinutes (), False, userdata//write to user role);            String encryptedticket = Formsauthentication.encrypt (AuthTicket);            System.Web.HttpCookie Authcookie = new System.Web.HttpCookie (Formsauthentication.formscookiename, encryptedticket); System.Web.HttpContext.Current.RespoNse.            Cookies.add (Authcookie);        Return redirecttoaction ("Index", "Home"); }

  

Code Download: Authorizationproject.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.