asp.net MVC 2 自定义用户角色权限设计

此地http://www.cnblogs.com/xiaoqi/archive/2011/01/24/1942880.html的博文,加上数据库,用entity framework稍作修改分享之。

实体模型如下图:

 

 DBUserAuthorizeAttribute.cs如下

DBUserAuthorizeAttribute.cs
  1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Web;
5 using System.Web.Mvc;
6
7 namespace MVCRole.Models
8 {
9 /// <summary>
10 /// 自定义AuthorizeAttribute
11 /// </summary>
12 public class DBUserAuthorizeAttribute : AuthorizeAttribute
13 {
14 private UserInfoEntities Database = new UserInfoEntities();
15 public override void OnAuthorization( AuthorizationContext filterContext ) {
16 if (filterContext == null) {
17 throw new ArgumentNullException( "filterContext" );
18 }
19 User user = filterContext.HttpContext.Session["CurrentUser"] as User;
20 string controller = filterContext.RouteData.Values["controller"].ToString();
21 string action = filterContext.RouteData.Values["action"].ToString();
22 var isAllowed = this.IsAllowed( user, controller, action );
23 if (!isAllowed) {
24 filterContext.HttpContext.Response.StatusCode = 401;
25 }
26
27 }
28
29 /// <summary>
30 /// 判断是否允许访问
31 /// </summary>
32 /// <param name="user">用户</param>
33 /// <param name="controller">控制器</param>
34 /// <param name="action">action</param>
35 /// <returns>是否允许访问</returns>
36 public bool IsAllowed( User user, string controller, string action ) {
37
38 // 找controllerAction
39 var controllerAction = Database.ControllerActions.FirstOrDefault( ca => ca.IsController == false && ca.Name == action && ca.ControllerName == controller );
40
41 //action无记录,找controller
42 if (controllerAction == null) {
43 controllerAction = Database.ControllerActions.FirstOrDefault( ca => ca.IsController && ca.Name == controller );
44 }
45
46 // 无规则
47 if (controllerAction == null) {
48 return true;
49 }
50
51
52 // 允许没有角色的:也就是说允许所有人,包括没有登录的用户
53 if (controllerAction.IsAllowedNoneRoles) {
54 return true;
55 }
56 if (user==null) {
57 return false;
58 }
59 // 允许所有角色:只要有角色,就可以访问
60 if (controllerAction.IsAllowedAllRoles) {
61 int count = Database.UserRoles.Count( ur => ur.UserID == user.ID );
62 if (count > 0) {
63 return true;
64 }
65 else {
66 return false;
67 }
68 }
69
70 // 选出action对应的角色
71 var actionRoles = Database.ControllerActionRoles.ToList().FindAll( ca => ca.ControllerActionID == controllerAction.ID );
72
73 if (actionRoles.Count == 0) {
74 // 角色数量为0,也就是说没有定义访问规则,默认允许访问
75 return true;
76 }
77 var userHavedRolesids = Database.UserRoles.ToList().FindAll( ur => ur.UserID == user.ID ).Select( ca => ca.RoleID );
78 // 查找禁止的角色
79 var notAllowedRoles = actionRoles.FindAll( r => !r.IsAllowed ).Select( ca => ca.RoleID );
80 if (notAllowedRoles.Count() > 0) {
81 foreach (int roleId in notAllowedRoles) {
82 // 用户的角色在禁止访问列表中,不允许访问
83 if (userHavedRolesids.Contains( roleId )) {
84 return false;
85 }
86 }
87 }
88 // 查找允许访问的角色列表
89 var allowRoles = actionRoles.FindAll( r => r.IsAllowed ).Select( ca => ca.RoleID ).ToList();
90 if (allowRoles.Count > 0) {
91 foreach (int roleId in allowRoles) {
92 // 用户的角色在访问的角色列表
93 if (userHavedRolesids.Contains( roleId )) {
94 return true;
95 }
96 }
97 }
98 // 默认禁止访问
99 return false;
100 }
101
102 }
103 }

 

  1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Web;
5 using System.Web.Mvc;
6
7 namespace MVCRole.Models
8 {
9 /// <summary>
10 /// 自定义AuthorizeAttribute
11 /// </summary>
12 public class DBUserAuthorizeAttribute : AuthorizeAttribute
13 {
14 private UserInfoEntities Database = new UserInfoEntities();
15 public override void OnAuthorization( AuthorizationContext filterContext ) {
16 var user = filterContext.HttpContext.Session["CurrentUser"] as User;
17
18 var controller = filterContext.RouteData.Values["controller"].ToString();
19 var action = filterContext.RouteData.Values["action"].ToString();
20 var isAllowed = this.IsAllowed( user, controller, action );
21
22 if (!isAllowed) {
23 filterContext.RequestContext.HttpContext.Response.Write( "无权访问" );
24 filterContext.RequestContext.HttpContext.Response.End();
25 }
26
27 }
28
29 /// <summary>
30 /// 判断是否允许访问
31 /// </summary>
32 /// <param name="user">用户</param>
33 /// <param name="controller">控制器</param>
34 /// <param name="action">action</param>
35 /// <returns>是否允许访问</returns>
36 public bool IsAllowed( User user, string controller, string action ) {
37
38 // 找controllerAction
39 var controllerAction = Database.ControllerActions.FirstOrDefault( ca => ca.IsController == false && ca.Name == action && ca.ControllerName == controller );
40
41 //action无记录,找controller
42 if (controllerAction == null) {
43 controllerAction = Database.ControllerActions.FirstOrDefault( ca => ca.IsController && ca.Name == controller );
44 }
45
46 // 无规则
47 if (controllerAction == null) {
48 return true;
49 }
50
51
52 // 允许没有角色的:也就是说允许所有人,包括没有登录的用户
53 if (controllerAction.IsAllowedNoneRoles) {
54 return true;
55 }
56 if (user==null) {
57 return false;
58 }
59 // 允许所有角色:只要有角色,就可以访问
60 if (controllerAction.IsAllowedAllRoles) {
61 int count = Database.UserRoles.Count( ur => ur.UserID == user.ID );
62 if (count > 0) {
63 return true;
64 }
65 else {
66 return false;
67 }
68 }
69
70 // 选出action对应的角色
71 var actionRoles = Database.ControllerActionRoles.ToList().FindAll( ca => ca.ControllerActionID == controllerAction.ID );
72
73 if (actionRoles.Count == 0) {
74 // 角色数量为0,也就是说没有定义访问规则,默认允许访问
75 return true;
76 }
77 var userHavedRolesids = Database.UserRoles.ToList().FindAll( ur => ur.UserID == user.ID ).Select( ca => ca.RoleID );
78 // 查找禁止的角色
79 var notAllowedRoles = actionRoles.FindAll( r => !r.IsAllowed ).Select( ca => ca.RoleID );
80 if (notAllowedRoles.Count() > 0) {
81 foreach (int roleId in notAllowedRoles) {
82 // 用户的角色在禁止访问列表中,不允许访问
83 if (userHavedRolesids.Contains( roleId )) {
84 return false;
85 }
86 }
87 }
88 // 查找允许访问的角色列表
89 var allowRoles = actionRoles.FindAll( r => r.IsAllowed ).Select( ca => ca.RoleID ).ToList();
90 if (allowRoles.Count > 0) {
91 foreach (int roleId in allowRoles) {
92 // 用户的角色在访问的角色列表
93 if (userHavedRolesids.Contains( roleId )) {
94 return true;
95 }
96 }
97 }
98 // 默认禁止访问
99 return false;
100 }
101
102 }
103 }
HomeController.cs
 1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Web;
5 using System.Web.Mvc;
6 using MVCRole.Models;
7
8 namespace MVCRole.Controllers
9 {
10 [HandleError]
11 [DBUserAuthorize]
12 public class HomeController : Controller
13 {
14 public ActionResult Index()
15 {
16 ViewData["Message"] = "欢迎使用 ASP.NET MVC!";
17
18 return View();
19 }
20 public ActionResult Admin()
21 {
22 ViewData["Message"] = "只有管理员才能访问!";
23
24 return View("Index");
25 }
26 public ActionResult User()
27 {
28 ViewData["Message"] = "只要是注册用户就能访问!";
29
30 return View("Index");
31 }
32 public ActionResult UserOnly()
33 {
34 ViewData["Message"] = "只能是User才能能访问!";
35
36 return View("Index");
37 }
38
39 public ActionResult Login(string user)
40 {
41 Session["CurrentUser"] = new UserInfoEntities().Users.FirstOrDefault(u => u.UserName == user);
42 if (Session["CurrentUser"] != null)
43 {
44 ViewData["Message"] = "你已登录为" + user;
45 }
46
47 return View("Index");
48 }
49
50
51 public ActionResult About()
52 {
53 return View();
54 }
55 }
56 }

流程:



posted @ 2012-02-20 16:18  一修先生  阅读(616)  评论(0编辑  收藏  举报