當我的一個項目到尾聲時,發現系統很多模組許可權有遺漏。部分模組許可權遺漏是由於前期開發速度太快,開發人員未先給模組加許可權而後再編寫該模組功能代碼。當我們檢查每個模組許可權是否遺漏時,噩夢來了---- 需要花費很長的時間(功能模組太多)。於是乎我寫了一個控制台許可權同步工具。整體思路如下:
其實在MVC內每個ActionResult 就可以看成一個新的模組,正因為這樣,因此我們可以對所有的模組進行統一管理。由於當前系統中許可權樹相對簡單:一個父級下多個子。所以只要指定好每個ActionResult 的父親即可。代碼如下:
其中 ParentModule 這個是自訂屬性類別似MVC的 [Authorize]。代碼如下:
1 [ParentModuleAttribute(ParentSystemModules.CustomerManage, "普通客戶")]
2 public ActionResult OrdinaryCustomer ()
3 {
4 return View();
5 }
6
7 [ParentModuleAttribute(ParentSystemModules.CustomerManage, "VIP客戶")]
8 public ActionResult VIPCustomer()
9 {
10 return View();
11 }
12
13 [ParentModuleAttribute(ParentSystemModules.TechnicalManage, "SQLServer")]
14 public ActionResult SQLSERVERManager()
15 {
16 return View();
17 }
18
19 [ParentModuleAttribute(ParentSystemModules.TechnicalManage, "ASP.NETMVC")]
20 public ActionResult MVCManager()
21 {
22 return View();
23 }
ParentModule 自訂特性:
1 [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
2 public class ParentModuleAttribute : Attribute
3 {
4
5 private ParentSystemModules _mType;
6 private string _moduleTitle;
7
8 public ParentModuleAttribute(ParentSystemModules mType, string moduleTitle)
9 {
10 _mType = mType;
11 _moduleTitle = moduleTitle;
12 }
13
14 public ParentSystemModules ModuleType
15 {
16 get
17 {
18 return _mType;
19 }
20 }
21
22 public string ModuleTitle
23 {
24 get
25 {
26 return _moduleTitle;
27 }
28 }
29
30 }
其中 ParentSystemModules 是所有的父模組枚舉,moduleTitle 為 當前模組名稱(可以改造成資源檔,方便日後擴充)。
以上我們每建完一個 ActionResult 隨即加上 ParentModuleAttribute 特性。便於下面我的同步工具可以
產生XML許可權結構。
如下:
查看自動產生的二級xml許可權結構:
整個思想主要取決於MVC自身的特點同時還應用到 .NET 特性、 反射、 LINQ 等技術。
同時還增加了檢測同一個許可權多次被不同的ActionResult(模組)增加的錯誤。
本文的例子請從 這裡 下載。