Subsequent article: Asp. Net MVC permission Control (2): Controller-Level Control
Rebuilding again! This time, the Controller and Action are verified.
Idea: The system has many function sets, which correspond to many controllers and actions.,Role allocation is a multi-function set.
First, build a basic data:
1. function 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> {c1 }}; var m22 = new SystemModule {Name = "Planning Information Management", Parent = m2, SystemModuleControllers = new List <SystemModuleController> {c2, c3, c4 }}; var m23 = new SystemModule {Name = "Planning Aid approval", Parent = m2, SystemModuleControllers = new List <SystemModuleController >{c5 }}; return new List <SystemModule> {m1, m2, m12, m21, m22, m23 };}}
2. Role initialization:
/// <Summary> /// role /// </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 controllers and actions of the system
/// <Summary> /// read all controllers and actions 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> SystemModuleActio Ns {get; set;} public static List <SystemModuleController> GetSystemModuleController () {var systemModuleControllers = new List <SystemModuleController> (); // read the Controller var types = Assembly in the project. load ("PRMMS. authorization "). getTypes (). where (B => B. baseType! = Null & B. baseType. name = "BaseController"); foreach (var type in types) {// mark the Controller var modules = type that requires permission verification. getCustomAttributes (typeof (ModuleAuthorizationAttribute), true); if (modules. length = 1) {// Controller name var controllerName = type. name. replace ("Controller", ""); // Controller description var description = string. empty; var attrs = type. getCustomAttributes (typeof (System. componentModel. D EscriptionAttribute), true); if (attrs. length> 0) {description = (attrs [0] as System. componentModel. descriptionAttribute ). description;} // get the Action var systemModuleControllerAction = new List <SystemModuleController> (); var actions = type. getMethods (). where (a =>. returnType! = Null &. returnType. name = "ActionResult"); foreach (var action in actions) {// Action Name var actionName = action. name; // Action Description var desc = string. empty; var act = action. getCustomAttributes (typeof (System. componentModel. descriptionAttribute), true); if (act. length> 0) {desc = (act [0] as System. componentModel. descriptionAttribute ). description;} systemModuleControllerAction. add (new SystemModuleController {ControllerName = controllerName, ActionName = actionName, Description = desc});} var systemModule = new SystemModuleController {ControllerName = controllerName, Description = description, SystemModuleActions = actions }; systemModuleControllers. add (systemModule) ;}return systemModuleControllers ;}}
After logging on to the system, initialize the permission and save it in 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 (20), 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 the permission var systemRole = SystemRole. init (model. roles); // cache permission AccountHelper. addCache (systemRole. systemModules); return RedirectToAction ("Index", "Home ");}
AccountHelper:
Public class AccountHelper {private const string CacheName = "SystemModules "; /// <summary> /// obtain 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. de Crypt (authCookie. value) ;}catch (Exception ex) {return null ;}} /// <summary> /// add cache /// </summary> /// <param name = "systemModules"> </param> public static void AddCache (List <systemModule> systemModules) {HttpContext. current. cache [CacheName] = systemModules ;} /// <summary> /// read the cache /// </summary> /// <returns> </returns> public static List <SystemModule> GetCache () {if (HttpContext. current. ca Che [CacheName] = null) {// re-construct the permission 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 the Controller and Action /// </summary> /// <param name = "controllerName"> </param> /// <param name = "actionName"> </param> // <retu Rns> </returns> public static bool ValidatePermission (string controllerName, string actionName) {var systemModules = 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 ;}}
Add an interception flag to the service Controller.
[LoginAllow] [PermissionFilter] public class BaseController: Controller {} [Description ("planning management Controller")] [ModuleAuthorization] public class PlanManagementController: BaseController {[Description ("Homepage")] 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 {// OnActionExecuted is called by the ASP. net mvc framework after the operation is executed. // OnActionExecuting is called by the ASP. net mvc framework before the operation method is executed. // OnResultExecuted is called by the ASP. net mvc framework after the operation result is executed. // OnResultExecuting is called by the ASP. net mvc framework before the operation result is executed. /// <Summary> /// it is called by the ASP. net mvc framework before the operation method is executed. /// </Summary> /// <param name = "filterContext"> </param> public override void OnActionExecuting (ActionExecutingContext filterContext) {// fcinfo = new filterContextInfo (filterContext); // process if (! This. AuthorizeCore (filterContext) {filterContext. RequestContext. HttpContext. Response. Redirect ("~ /Account/Login ");}} /// <summary> //// permission judgment business logic // </summary> /// <param name = "filterContext"> </param> /// <returns> </returns> protected virtual bool AuthorizeCore (ActionExecutingContext filterContext) {object [] filter; // verify whether the current Action is an anonymous access Action filter = filterContext. controller. getType (). getCustomAttributes (typeof (AnonymousAttribute), true); if (filter. length = 1) {return true;} // verify the current Ac Whether tion is a permission control page Action filter = filterContext. controller. getType (). getCustomAttributes (typeof (ModuleAuthorizationAttribute), true); if (filter. length = 1) {// obtain the controllerName var controllerName = filterContext. routeData. values ["controller"]. toString (); // obtain the ACTION name var actionName = filterContext. routeData. values ["action"]. toString (); return AccountHelper. validatePermission (controllerName, acti OnName);} // verify whether the current Action is a login user Action filter = filterContext. controller. getType (). getCustomAttributes (typeof (loginallowattrites), true); if (filter. length = 1) {return HttpContext. current. user. identity. isAuthenticated;} throw new Exception ("user verification failed! ");}}
Download the code: PRMMS.Authorization.zip