asp.net MVC 权限设计(续)
生活随笔
收集整理的這篇文章主要介紹了
asp.net MVC 权限设计(续)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
asp.net MVC 權限設計一文中沒有demo放出來,應大家的要求,這里補充上文并放出demo。
?
幾點說明:
?
??? 1、基于將角色與controller、action相關聯來判斷用戶是否有權
??? 2、通過自定義AuthorizeAttribute實現
??? 3、demo 僅供參考,一些規則可以根據實際情況重新定義
?
簡明需求
1、可以對每個action實現權限控制,并且可以在數據庫動態配置
2、權限分為允許所有人訪問、允許注冊用戶訪問、允許\禁止特定角色人訪問
?
數據庫設計
?
在demo里不使用數據庫,這里給出表對應的類
/// /// 控制器和Action/// public class ControllerAction{public int Id{get;set;}public string Name{get;set;}/// /// IsController是指是否是controller,如果為false,/// 表示是action,那么controllerName字段就派上用場了/// public bool IsController{get;set;}/// /// 控制器名稱/// 如果IsController為false,該項不能為空/// public string ControllName{get;set;}/// /// 是指是否允許沒有權限的人訪問 /// public bool IsAllowedNoneRoles{get;set;}/// /// 是否允許有角色的人訪問 /// public bool IsAllowedAllRoles{get;set;}}/// /// 用戶與角色的關聯表/// public class ControllerActionRole{public int Id{get;set;}/// /// 對應的ControllerAction編號/// public int ControllerActioId{get;set;}/// /// 對應的角色編號/// public int RoleId{get;set;}/// /// IsAllowed表示包含RoleId的用戶是否有權限訪問ControllerActioId/// public bool IsAllowed{get;set;}}/// /// 角色/// public class Role{public int Id{get;set;}public string Name{get;set;}public string Description{get;set;}}/// /// 用戶/// public class User{public int Id{get;set;}public string Name{get;set;}}/// /// 用戶與角色的關聯表/// public class UserRole{public int Id{get;set;}public int UserId{get;set;}public int RoleId{get;set;}}核心流程
?
我們見一個Database類來模擬數據庫
/// /// /// 模擬數據庫/// public class Database{public static List Users;public static List Roles;public static List UserRoles;public static List ControllerActions;public static List ControllerActionRoles;static Database(){// 初始化用戶Users = new List(){new User(){Id=1,Name="Admin"},new User(){Id=2,Name ="User"},new User(){Id=3,Name="Guest"}};Roles = new List(){new Role() {Id=1,Name="Administrator"},new Role() {Id=2,Name="User"}};UserRoles = new List(){new UserRole(){Id=1,RoleId=1,UserId=1}, //管理員new UserRole(){Id=2,RoleId=2,UserId=2} //用戶};ControllerActions = new List(){new ControllerAction(){Id=1,Name="Index",IsController=true,IsAllowedNoneRoles=true,IsAllowedAllRoles=true}, // /Home 允許所有人訪問new ControllerAction(){Id=2,ControllName="Home",Name="Admin",IsController=false,IsAllowedNoneRoles=false,IsAllowedAllRoles = false}, // /Home/Admin 管理員才能訪問new ControllerAction(){Id=3,ControllName="Home",Name="User",IsController=false,IsAllowedNoneRoles=false,IsAllowedAllRoles = true}, // /Home/User 有角色的人才能訪問new ControllerAction(){Id=4,ControllName="Home",Name="UserOnly",IsController=false,IsAllowedNoneRoles=false,IsAllowedAllRoles = false}, // /Home/UserOnly 用戶才能訪問};ControllerActionRoles = new List() { new ControllerActionRole(){ Id=1,ControllerActioId = 2,RoleId = 1,IsAllowed = true }, // 管理員才能訪問new ControllerActionRole(){ Id=2,ControllerActioId = 4,RoleId = 2,IsAllowed = true } // USER才能訪問};}}來看我們的主要代碼
/// /// 自定義AuthorizeAttribute/// public class UserAuthorizeAttribute : AuthorizeAttribute{public override void OnAuthorization(AuthorizationContext filterContext){var user = filterContext.HttpContext.Session["CurrentUser"] as User;// 用戶為空,賦予Guestif (user == null){user = Database.Users.Find(u => u.Name == "Guest");}var controller = filterContext.RouteData.Values["controller"].ToString();var action = filterContext.RouteData.Values["action"].ToString();var isAllowed = this.IsAllowed(user, controller, action);if (!isAllowed){filterContext.RequestContext.HttpContext.Response.Write("無權訪問");filterContext.RequestContext.HttpContext.Response.End();}}/// /// 判斷是否允許訪問/// /// ?用戶/// ?控制器/// ?action/// 是否允許訪問public bool IsAllowed(User user, string controller, string action){// 找controllerActionvar controllerAction = Database.ControllerActions.Find(ca => ca.IsController == false && ca.Name == action && ca.ControllName == controller);//action無記錄,找controllerif (controllerAction == null){controllerAction = Database.ControllerActions.Find(ca => ca.IsController && ca.Name == controller);}// 無規則if (controllerAction == null){return true;}// 允許沒有角色的:也就是說允許所有人,包括沒有登錄的用戶 if (controllerAction.IsAllowedNoneRoles){return true;}// 允許所有角色:只要有角色,就可以訪問 if (controllerAction.IsAllowedAllRoles){var roles = Database.UserRoles.FindAll(ur => ur.UserId == user.Id);if (roles.Count > 0){return true;}else{return false;}}// 選出action對應的角色 var actionRoles = Database.ControllerActionRoles.FindAll(ca => ca.ControllerActioId == controllerAction.Id).ToList();if (actionRoles.Count == 0){// 角色數量為0,也就是說沒有定義訪問規則,默認允許訪問 return true;}var userHavedRolesids = Database.UserRoles.FindAll(ur => ur.UserId == user.Id).Select(ca => ca.RoleId).ToList();// 查找禁止的角色 var notAllowedRoles = actionRoles.FindAll(r => !r.IsAllowed).Select(ca => ca.RoleId).ToList();if (notAllowedRoles.Count > 0){foreach (int roleId in notAllowedRoles){// 用戶的角色在禁止訪問列表中,不允許訪問 if (userHavedRolesids.Contains(roleId)){return false;}}}// 查找允許訪問的角色列表 var allowRoles = actionRoles.FindAll(r => r.IsAllowed).Select(ca => ca.RoleId).ToList();if (allowRoles.Count > 0){foreach (int roleId in allowRoles){// 用戶的角色在訪問的角色列表 if (userHavedRolesids.Contains(roleId)){return true;}}}// 默認禁止訪問return false;}}測試
[HandleError][UserAuthorize]public class HomeController : Controller{public ActionResult Index(){ViewData["Message"] = "歡迎使用 ASP.NET MVC!";return View();}public ActionResult Admin(){ViewData["Message"] = "只有管理員才能訪問!";return View("Index");}public ActionResult User(){ViewData["Message"] = "只要是注冊用戶就能訪問!";return View("Index");}public ActionResult UserOnly(){ViewData["Message"] = "只能是User才能能訪問!";return View("Index");}public ActionResult Login(string user){Session["CurrentUser"] = Database.Users.Find(u => u.Name == user);if (Session["CurrentUser"] != null){ViewData["Message"] = "你已登錄為" + user;}return View("Index");}public ActionResult About(){return View();}}?
1、登錄為Admin
?
訪問Admin
?
訪問User
?
訪問UserOnly
?
2、登錄為User
?
訪問Admin
?
訪問User
訪問UserOnly
?
demo下載 MVCRole.rar
轉載于:https://www.cnblogs.com/xiaoqi/archive/2011/01/24/1942880.html
總結
以上是生活随笔為你收集整理的asp.net MVC 权限设计(续)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 398元/年 车主投诉哈弗F7车联网变相
- 下一篇: HDU 2095 find your p