ASP.NET MVC权限验证 封装类

写该权限类主要目地

为了让权限配置更加的灵活,可以根据SQL、json、或者XML的方式来动态进行页面的访问控制,以及没有权限的相关跳转。

使用步骤

1、要建一个全局过滤器

1
2
3
4
5
6
7
//受权过滤器
 public class AuthorizeFilter : AuthorizeAttribute
 {
     public override void OnAuthorization(AuthorizationContext filterContext)
     {
     }
}

  

2、Gobal里注册 GlobalFilters.Filters.Add(new AuthorizeFilter());该过该全局过滤器

1
2
3
4
5
6
7
8
9
protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        GlobalFilters.Filters.Add(new AuthorizeFilter());
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }

  

3、在过滤器中调用 SystemAuthorizeService.Start实现

(1)使用对象进行权限验证

1
<br><span style="line-height: 1.5;"><br><br></span>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public override void OnAuthorization(AuthorizationContext filterContext)
       {
           
           List<SystemAuthorizeModel> smList = new List<SystemAuthorizeModel>()
           {
               //用户1,2,3可以访问 area为admin  所有权限
               new SystemAuthorizeModel() { SystemAuthorizeType= SystemAuthorizeType.Area, AreaName="admin" , UserKeyArray=new dynamic[] { 1,2,3 /*用户授权数组*/} },
 
 
               //用户8,7可以访问 area为admin  控制器为:center   所有权限
               new SystemAuthorizeModel() { SystemAuthorizeType= SystemAuthorizeType.Controller, AreaName="admin" , ControllerName="center", UserKeyArray=new dynamic[] { 8,7 /*用户授权数组*/} },
 
                
               //用户1可以访问为 area为:null 控制器为:home  操作为:about 的请求
               new SystemAuthorizeModel() { SystemAuthorizeType= SystemAuthorizeType.Action,  ControllerName="home" , ActionName="about" , UserKeyArray=new dynamic[] { 1 } },
 
 
               //给用户100和110所有页面权限
               new SystemAuthorizeModel() { SystemAuthorizeType= SystemAuthorizeType.All, UserKeyArray=new dynamic[] { 100,110 } }
 
           };
 
 
           SystemAuthorizeErrorRedirect sr = new SystemAuthorizeErrorRedirect();
           sr.DefaultUrl = "/user/login";//没有权限都跳转到DefaultUrl
          //sr.ItemList=xx 设置更详细的跳转
 
 
           SystemAuthorizeService.Start(filterContext, smList, sr, () =>
           {
 
               //获取用户ID
               return 1; //用户ID为1,作为DEMO写死 ,当然了可以是SESSION也可以是COOKIES等 这儿就不解释了
           });
       }

  

1
 

(2)使用JSON转成对象进行验证

[
{
"SystemAuthorizeType": 1,
"AreaName": "admin",
"ControllerName": "center",
"ActionName": null,
"UserKeyArray": [
1,
2,
3
]
},
{
"SystemAuthorizeType": 1,
"AreaName": "admin",
"ControllerName": "center",
"ActionName": null,
"UserKeyArray": [
8,
7
]
},
{
"SystemAuthorizeType": 3,
"AreaName": null,
"ControllerName": "home",
"ActionName": "about",
"UserKeyArray": [
1
]
},
{
"SystemAuthorizeType": 0,
"AreaName": null,
"ControllerName": null,
"ActionName": null,
"UserKeyArray": [
100,
110
]
}
]

1
<br><br>

SystemAuthorizeService代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
 
namespace Idea.Models.Filters
{
    /// <summary>
    /// 系统授权服务
    /// 作者:sunkaixuan
    /// 时间:2015-10-25
    /// </summary>
    public class SystemAuthorizeService
    {
        /// <summary>
        /// 启动系统授权
        /// </summary>
        /// <param name="filterContext"></param>
        /// <param name="SystemAuthorizeList">所有验证项</param>
        /// <param name="errorRediect">没有权限跳转地址</param>
        /// <param name="GetCurrentUserId">获取当前用户ID</param>
        public static void Start(AuthorizationContext filterContext, List<SystemAuthorizeModel> systemAuthorizeList, SystemAuthorizeErrorRedirect errorRediect, Func<object> GetCurrentUserKey)
        {
 
 
            if (errorRediect == null)
            {
                throw new ArgumentNullException("SystemAuthorizeService.Start.errorRediect");
            }
            if (systemAuthorizeList == null)
            {
                throw new ArgumentNullException("SystemAuthorizeService.Start.systemAuthorizeList");
            }
 
            //全部小写
            foreach (var it in systemAuthorizeList)
            {
                it.ControllerName = it.ControllerName.ToLower();
                it.ActionName = it.ActionName.ToLower();
                it.AreaName = it.AreaName.ToLower();
            }
 
 
            //声名变量
            var context = filterContext.HttpContext;
            var request = context.Request;
            var response = context.Response;
            string actionName = filterContext.ActionDescriptor.ActionName.ToLower();
            string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.ToLower();
            string areaName = null;
            bool isArea = filterContext.RouteData.DataTokens["area"] != null;
 
 
            //变量赋值
            if (isArea)
                areaName = filterContext.RouteData.DataTokens["area"].ToString().ToLower();
 
 
            //函数方法
            #region 函数方法
            Action<stringstringstring> Redirect = (action, controller, area) =>
            {
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = controller, action = action, area = area }));
            };
            Action<string> RedirectUrl = url =>
            {
                filterContext.Result = new RedirectResult(url);
            };
            #endregion
 
 
            Func<SystemAuthorizeErrorRedirectItemList, bool> redirectActionExpression = it => it.SystemAuthorizeType == SystemAuthorizeType.Action && it.Area == areaName && it.Controller == controllerName && it.Action == actionName;
            Func<SystemAuthorizeErrorRedirectItemList, bool> redirectControllerExpression = it => it.SystemAuthorizeType == SystemAuthorizeType.Action && it.Area == areaName && it.Controller == controllerName;
            Func<SystemAuthorizeErrorRedirectItemList, bool> redirectAreaExpression = it => it.SystemAuthorizeType == SystemAuthorizeType.Action && it.Area == areaName;
 
 
            Func<SystemAuthorizeModel, bool> actionExpression = it => it.SystemAuthorizeType == SystemAuthorizeType.Action && it.AreaName == areaName && it.ControllerName == controllerName && it.ActionName == actionName;
            Func<SystemAuthorizeModel, bool> controllerExpression = it => it.SystemAuthorizeType == SystemAuthorizeType.Controller && it.AreaName == areaName && it.ControllerName == controllerName;
            Func<SystemAuthorizeModel, bool> areaExpression = it => it.SystemAuthorizeType == SystemAuthorizeType.Area && it.AreaName == areaName;
 
            dynamic userId = GetCurrentUserKey();
 
            //所有权限
            bool isAllByUuserKey = IsAllByUserKey(systemAuthorizeList, userId);
            bool isAreaByUserKey = IsAreaByUserKey(systemAuthorizeList, areaName, userId);
            bool isControllerByUserKey = IsControllerByUserKey(systemAuthorizeList, areaName, controllerName, userId);
            bool isActionByUserKey = IsActionByUserKey(systemAuthorizeList, areaName, controllerName, actionName, userId);
            //有权限
            var hasPower = (isAllByUuserKey || isActionByUserKey || isControllerByUserKey || isAreaByUserKey);
            //需要验证
            var mustValidate = systemAuthorizeList.Any(actionExpression) || systemAuthorizeList.Any(controllerExpression) || systemAuthorizeList.Any(areaExpression);
 
            if (!hasPower && mustValidate)
            {
                ErrorRediect(errorRediect, RedirectUrl, redirectActionExpression, redirectControllerExpression, redirectAreaExpression);
            }
 
        }
 
        private static void ErrorRediect(SystemAuthorizeErrorRedirect errorRediect, Action<string> RedirectUrl, Func<SystemAuthorizeErrorRedirectItemList, bool> actionExpression, Func<SystemAuthorizeErrorRedirectItemList, bool> controllerExpression, Func<SystemAuthorizeErrorRedirectItemList, bool> areaExpression)
        {
            if (errorRediect.ItemList == null)
            {//返回默认错误地址
                RedirectUrl(errorRediect.DefaultUrl);
            }
            else if (errorRediect.ItemList.Any(actionExpression))
            {
                var red = errorRediect.ItemList.Single(actionExpression);
                RedirectUrl(red.ErrorUrl);
            }
            else if (errorRediect.ItemList.Any(controllerExpression))
            {
                var red = errorRediect.ItemList.Single(controllerExpression);
                RedirectUrl(red.ErrorUrl);
            }
            else if (errorRediect.ItemList.Any(areaExpression))
            {
                var red = errorRediect.ItemList.Single(areaExpression);
                RedirectUrl(red.ErrorUrl);
            }
            else if (errorRediect.ItemList.Any(it => it.SystemAuthorizeType == SystemAuthorizeType.All))
            {
                var red = errorRediect.ItemList.Single(it => it.SystemAuthorizeType == SystemAuthorizeType.All);
                RedirectUrl(red.ErrorUrl);
            }
            else
            {
                RedirectUrl(errorRediect.DefaultUrl);
            }
        }
 
        private static bool IsAllByUserKey(List<SystemAuthorizeModel> systemAuthorizeList, object userKey)
        {
            var hasAll = systemAuthorizeList.Any(it => it.SystemAuthorizeType == SystemAuthorizeType.All);
            if (hasAll)
            {
                if (systemAuthorizeList.Any(it => it.UserKeyArray != null && it.UserKeyArray.Contains(userKey)))
                {
                    return true;
                }
            }
 
            return false;
        }
        private static bool IsAreaByUserKey(List<SystemAuthorizeModel> systemAuthorizeList, string area, object userKey)
        {
 
            if (systemAuthorizeList.Any(it => it.AreaName == area && it.SystemAuthorizeType == SystemAuthorizeType.Area)) //是否存在验证级别为Area的验证
            {
                var isContains = systemAuthorizeList.Any(it => it.AreaName == area && it.SystemAuthorizeType == SystemAuthorizeType.Area && it.UserKeyArray.Contains(userKey));
                return isContains;
            }
            return false;
        }
 
 
        private static bool IsControllerByUserKey(List<SystemAuthorizeModel> systemAuthorizeList, string area, string controller, object userKey)
        {
            if (systemAuthorizeList.Any(it => it.AreaName == area && it.ControllerName == controller && it.SystemAuthorizeType == SystemAuthorizeType.Controller)) //是否存在验证级别为Controller的验证
            {
                var isContains = systemAuthorizeList.Any(it => it.AreaName == area && it.ControllerName == controller && it.SystemAuthorizeType == SystemAuthorizeType.Controller && it.UserKeyArray.Contains(userKey));
                return isContains;
            }
            return false;
        }
 
 
 
 
        private static bool IsActionByUserKey(List<SystemAuthorizeModel> systemAuthorizeList, string area, string controller, string action, dynamic userKey)
        {
 
            if (systemAuthorizeList.Any(it => it.AreaName == area && it.ControllerName == controller && it.ActionName == action && it.SystemAuthorizeType == SystemAuthorizeType.Action)) //是否存在验证级别为action的验证
            {
                return systemAuthorizeList.Any(it => it.AreaName == area && it.ControllerName == controller && it.ActionName == action && it.SystemAuthorizeType == SystemAuthorizeType.Action && it.UserKeyArray.ToString().Contains(userKey.ToString()));
            }
 
            return false;
        }
    }
 
 
 
 
 
 
    /// <summary>
    /// 用户访问需要授权的项
    /// </summary>
    public class SystemAuthorizeModel
    {
        /// <summary>
        /// 验证类型
        /// </summary>
        public SystemAuthorizeType SystemAuthorizeType { getset; }
        /// <summary>
        /// 用户拥有权限访问的Area
        /// </summary>
        public string AreaName { getset; }
        /// <summary>
        /// 用户拥有权限访问的Controller
        /// </summary>
        public string ControllerName { getset; }
        /// <summary>
        /// 用户拥有权限访问的Actioin
        /// </summary>
        public string ActionName { getset; }
        /// <summary>
        /// 用户ID
        /// </summary>
        public dynamic[] UserKeyArray { getset; }
 
    }
 
    /// <summary>
    /// 如果没有权限返回地址
    /// </summary>
    public class SystemAuthorizeErrorRedirect
    {
        /// <summary>
        /// 默认值
        /// </summary>
        public string DefaultUrl { getset; }
 
        public List<SystemAuthorizeErrorRedirectItemList> ItemList { getset; }
    }
 
    public class SystemAuthorizeErrorRedirectItemList
    {
        /// <summary>
        /// 验证类型
        /// </summary>
        public SystemAuthorizeType SystemAuthorizeType { getset; }
        public string Controller { getset; }
        public string Action { getset; }
        public string Area { getset; }
 
        public string ErrorUrl { getset; }
 
    }
 
    /// <summary>
    /// 验证类型
    /// </summary>
    public enum SystemAuthorizeType
    {
        /// <summary>
        /// 所有权限
        /// </summary>
        All = 0,
        /// <summary>
        ///验证Area
        /// </summary>
        Area = 1,
        /// <summary>
        /// 验证Area和Controller
        /// </summary>
        Controller = 2,
        /// <summary>
        /// 验证Area和Controller和Action
        /// </summary>
        Action = 3,
        /// <summary>
        /// 没有权限
        /// </summary>
        No = 4
 
    }
}

  

 
分类: C#语法糖

NET MVC权限验证的更多相关文章

  1. ASP.NET MVC权限验证 封装类

    写该权限类主要目地 为了让权限配置更加的灵活,可以根据SQL.json.或者XML的方式来动态进行页面的访问控制,以及没有权限的相关跳转. 使用步骤 1.要建一个全局过滤器 //受权过滤器 publi ...

  2. C# MVC权限验证

    前言 之前一直没怎么接触过权限验证这块,刚好公司老平台改版,就有了这篇权限验证.此篇文章大致讲解下 精确到按钮级别的验证如何实现.以及权限验证设计的参考思路(菜鸟一枚,大神勿喷). 在开发大项目的时候 ...

  3. 关于filter web api mvc 权限验证 这里说的够详细了。。。

    参考:http://www.cnblogs.com/willick/p/3331520.html Filter(筛选器)是基于AOP(面向方面编程)的设计,它的作用是对MVC框架处理客户端请求注入额外 ...

  4. MVC权限验证过滤器

    Action属性,权限设定属性   [AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)] ...

  5. .net web mvc 权限验证

    这里分享MVC的权限验证,内容中可能存在一些,莫名其妙的方法,那些是以前封装好的,大致可以根据方法名称知道他的意思. using Game.Entity; using Game.Entity.Plat ...

  6. mvc 权限验证

    using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.We ...

  7. MVC权限验证之ActionFilterAttribute

    参考:http://www.cnblogs.com/waitingfor/archive/2011/12/27/2303784.html ActionFilterAttribute是Action过滤类 ...

  8. mvc权限验证--AuthorizeAttribute

    在做后台管理时用户登录后就需要验证哪些权限了,没有登录的就直接退出到登录页面. 系统有自带的权限[Authorize],可用于几个地方: 1.将属性[Authorize]置于相关的action上方,验 ...

  9. Asp.net MVC 权限验证,以及是否允许匿名访问

    public class CheckUserAttribute : ActionFilterAttribute, IAuthorizationFilter { public void OnAuthor ...

随机推荐

  1. 第一章 andrid visdio 安装

    第一章   andrid visdio 安装与环境搭建 一.Android Studio简介 Android Studio是Google新发布的Android应用程序开发环境,Android Stud ...

  2. login控件“您的登录尝试不成功。请重试”的解决方法

    原文:login控件"您的登录尝试不成功.请重试"的解决方法 遇到login控件“您的登录尝试不成功.请重试”报错之后,在网上找了很久,也按照如下帖子设置了 application ...

  3. 一般报java.lang.NullPointerException的原因有以下几种

    一般报java.lang.NullPointerException的原因有以下几种: ·字符串变量未初始化: ·接口类型的对象没有用具体的类初始化,比如: List lt; 会报错 List lt = ...

  4. mysql copy复制拷贝表数据及结构的几种方式(转)

    mysql拷贝表操作我们会常常用到,下面就为您详细介绍几种mysql拷贝表的方式,希望对您学习mysql拷贝表方面能够有所帮助.假如我们有以下这样一个表:id username password--- ...

  5. BZOJ 2783 JLOI 2012 树 乘+二分法

    标题效果:鉴于一棵树和一个整数s,问中有树木几个这样的路径,点和担保路径==s,深度增量点. 这一数额的输出. 思维:用加倍的想法,我们可以O(logn)在时间找点他第一n.因为点权仅仅能是正的,满足 ...

  6. JQuery打印

    jquery.jqprint-0.3.js JQuery提供的局部打印功能: <input type="button" value="打印" onclic ...

  7. js调用百度地图接口

    原文:js调用百度地图接口 这是前几天公司做的新项目,上面需要用到地图的数据.第一次做这类型的东西没啥思路,咱们经理说,这东西简单,截个图存文件夹里调整好尺寸,数据库里存上图片的地址动态调用就行了.心 ...

  8. 标准I/O缓冲:全缓冲、行缓冲、无缓冲

    说明:我仅仅对网络资源进行了整合,方便学习-.- 基于流的操作终于会调用read或者write函数进行I/O操作.为了使程序的执行效率最高,流对象一般会提供缓冲区,以降低调用系统I/O库函数的次数. ...

  9. 玩转Web之Json(三)-----easy ui怎么把前台显示的dataGird中的所有数据序列化为json,返回到后台并解析

    最近做一个项目时,需要在dataGird中插入<input>,即文本输入框,当点击提交时,需要把文本框里填的数据返以及其他列的一些信息以json数组的格式返回到后台,虽然我实现了该功能,但 ...

  10. 一道看似简单的sql需求(转)

    听说这题难住大批高手,你也来试下吧.ps:博问里的博友提出的. 原始数据 select * from t_jeff t  简单排序后数据 select * from t_jeff t order by ...