1.資料結構

0Z0556431-0  

Mad_Popedom為許可權表,Control記錄控制器名,Action記錄動作名。
Mad_Role為角色表。
 
2.許可權控制的實現
此處使用比較簡單AOP方式,用MVC的Filter實現,代碼如下

 

1 using System.Collections.Generic;
2 using System.Web.Mvc;
3 using Madnet.Model.MadAdmin;
4 using Madnet.BLL.MadAdmin;
5
6 namespace Madnet.Controllers.MadAdmin
7 {
8 public class SupportFilterAttribute : ActionFilterAttribute
9 {
10 private bool _IsLogin = true;
11 /// <summary>
12 /// 是否需要登錄
13 /// </summary>
14 public bool IsLogin
15 {
16 set
17 {
18 _IsLogin = value;
19 }
20 get
21 {
22 if (System.Configuration.ConfigurationManager.AppSettings["IsLogin"] != null)
23 {
24 bool.TryParse(System.Configuration.ConfigurationManager.AppSettings["IsLogin"].ToString(), out _IsLogin);
25 }
26 return _IsLogin;
27 }
28 }
29 public override void OnActionExecuting(ActionExecutingCoNtext filterCoNtext)
30 {
31 string controllerName = (string)filterCoNtext.RouteData.Values["controller"];
32 string actionName = (string)filterCoNtext.RouteData.Values["action"];
33
34 if (IsLogin && filterCoNtext.HttpCoNtext.Session["Login_User"] == null)
35 {
36 filterCoNtext.HttpCoNtext.Response.Redirect(new UrlHelper(filterCoNtext.RequestCoNtext).Action("Login", "Default"));
37 filterCoNtext.Result = new EmptyResult();
38 }
39 else if (IsLogin && filterCoNtext.HttpCoNtext.Session["Login_User"] != null)
40 {
41 Mad_User user = filterCoNtext.HttpCoNtext.Session["Login_User"] as Mad_User;
42 if (!user.is_super)
43 {
44 if (!GetPopedom(user).Exists(p => p.Controller_Name == controllerName.ToLower() && p.Action_Name == actionName.ToLower()))
45 {
46 filterCoNtext.HttpCoNtext.Response.Write("沒有許可權");
47 filterCoNtext.Result = new EmptyResult();
48 }
49
50 }
51 }
52
53 }
54 /// <summary>
55 /// 獲取當前使用者所有有許可權執行的動作
56 /// </summary>
57 /// <returns></returns>
58 public List<Atmodel> GetPopedom(Mad_User user)
59 {
60 List<Atmodel> ats = new List<Atmodel>();
61 List<Mad_Popedom> pops = Mad_PopedomBLL.GetPopedombyUser(user.user_id);
62 foreach (Mad_Popedom pop in pops)
63 {
64 ats.Add(new AtModel() { Controller_Name = pop.Control, Action_Name = pop.Action });
65 }
66 return ats;
67 }
68
69 }
70 }
 
解釋一下,上面的代碼就是在執行前,先獲取登錄使用者可以運行的Controller-Action,然後和當前需要執行的Controller-Action比較,如存在,即通過,否則為沒有許可權執行。
3.為動作添加許可權
為簡單起見,對於Controller層我是獨立出來一個類庫的,好處是等會為角色添加許可權的時候我們不需要手動輸入,只要反射dll就可以了。

0Z0554G0-3  

如圖所示,凡需要許可權控制的函數,只需要添加[SupportFilter]特性就可以了,當然這種方式只能控制到Action級。
 
4.為角色額添加許可權
這個比較簡單,只需要把角色和許可權關聯起來就可以了,這裡我是用反射Controller層dll實現。
Web.config

0Z0554c5-4  

Global.asax.cs

0Z0553408-5  

Madnet.Controllers.Test即為Controller層的dll

0Z0552649-6  

Test為Controller名,index為Action名,選擇role2可以訪問的Action,提交到資料庫即可。此圖表示role2擁有Test1Controller的存取權限,但是沒有Test2Controller,Test3Controller的存取權限。
5.結束
上面4步即已完成基本的許可權控制。可以在此基礎上加上使用者組,使用者,功能表等管理,可實現」使用者-角色-許可權」的自由組合,一個簡單的通用後臺大概就是這樣了。
 0Z0555I2-7  
arrow
arrow
    全站熱搜

    戮克 發表在 痞客邦 留言(0) 人氣()