博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ASP.NET MVC权限验证 封装类
阅读量:6160 次
发布时间:2019-06-21

本文共 10757 字,大约阅读时间需要 35 分钟。

 

写该权限类主要目地

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

 

使用步骤

 

1、要建一个全局过滤器

//受权过滤器    public class AuthorizeFilter : AuthorizeAttribute    {        public override void OnAuthorization(AuthorizationContext filterContext)        {         }   }

  

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

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)使用对象进行权限验证

 
public override void OnAuthorization(AuthorizationContext filterContext)        {                       List
smList = new List
() { //用户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等 这儿就不解释了 }); }

  

 

(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
]
}
]

 

SystemAuthorizeService代码:

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{    ///     /// 系统授权服务    /// 作者:sunkaixuan    /// 时间:2015-10-25    ///     public class SystemAuthorizeService    {        ///         /// 启动系统授权        ///         ///         /// 所有验证项        /// 没有权限跳转地址        /// 获取当前用户ID        public static void Start(AuthorizationContext filterContext, List
systemAuthorizeList, SystemAuthorizeErrorRedirect errorRediect, Func
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
Redirect = (action, controller, area) => { filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = controller, action = action, area = area })); }; Action
RedirectUrl = url => { filterContext.Result = new RedirectResult(url); }; #endregion Func
redirectActionExpression = it => it.SystemAuthorizeType == SystemAuthorizeType.Action && it.Area == areaName && it.Controller == controllerName && it.Action == actionName; Func
redirectControllerExpression = it => it.SystemAuthorizeType == SystemAuthorizeType.Action && it.Area == areaName && it.Controller == controllerName; Func
redirectAreaExpression = it => it.SystemAuthorizeType == SystemAuthorizeType.Action && it.Area == areaName; Func
actionExpression = it => it.SystemAuthorizeType == SystemAuthorizeType.Action && it.AreaName == areaName && it.ControllerName == controllerName && it.ActionName == actionName; Func
controllerExpression = it => it.SystemAuthorizeType == SystemAuthorizeType.Controller && it.AreaName == areaName && it.ControllerName == controllerName; Func
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
RedirectUrl, Func
actionExpression, Func
controllerExpression, Func
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
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
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
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
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; } } ///
/// 用户访问需要授权的项 /// public class SystemAuthorizeModel { ///
/// 验证类型 /// public SystemAuthorizeType SystemAuthorizeType { get; set; } ///
/// 用户拥有权限访问的Area /// public string AreaName { get; set; } ///
/// 用户拥有权限访问的Controller /// public string ControllerName { get; set; } ///
/// 用户拥有权限访问的Actioin /// public string ActionName { get; set; } ///
/// 用户ID /// public dynamic[] UserKeyArray { get; set; } } ///
/// 如果没有权限返回地址 /// public class SystemAuthorizeErrorRedirect { ///
/// 默认值 /// public string DefaultUrl { get; set; } public List
ItemList { get; set; } } public class SystemAuthorizeErrorRedirectItemList { ///
/// 验证类型 /// public SystemAuthorizeType SystemAuthorizeType { get; set; } public string Controller { get; set; } public string Action { get; set; } public string Area { get; set; } public string ErrorUrl { get; set; } } ///
/// 验证类型 /// public enum SystemAuthorizeType { ///
/// 所有权限 /// All = 0, ///
///验证Area /// Area = 1, ///
/// 验证Area和Controller /// Controller = 2, ///
/// 验证Area和Controller和Action /// Action = 3, ///
/// 没有权限 /// No = 4 }}

  

转载地址:http://oqafa.baihongyu.com/

你可能感兴趣的文章
在OSCHINA上的第一篇博文,以后好好学习吧
查看>>
Spring常用注解
查看>>
linux:yum和apt-get的区别
查看>>
Sentinel 1.5.0 正式发布,引入 Reactive 支持
查看>>
数据库之MySQL
查看>>
2019/1/15 批量删除数据库相关数据
查看>>
数据类型的一些方法
查看>>
Webpack 2 中一些常见的优化措施
查看>>
移动端响应式
查看>>
js中var、let、const的区别
查看>>
简洁优雅地实现夜间模式
查看>>
react学习总结
查看>>
在soapui上踩过的坑
查看>>
MySQL的字符集和字符编码笔记
查看>>
ntpd同步时间
查看>>
Maven编译时跳过Test
查看>>
Spring Boot 整合Spring Security 和Swagger2 遇到的问题小结
查看>>
Apache通过mod_php5支持PHP
查看>>
java学习:jdbc连接示例
查看>>
Silverlight 如何手动打包xap
查看>>