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