ASP.NET MVC权限验证 封装类
写该权限类主要目地
为了让权限配置更加的灵活,可以根据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<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等 这儿就不解释了
});
}
(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
{
/// <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<string, string, string> 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 { get; set; }
/// <summary>
/// 用户拥有权限访问的Area
/// </summary>
public string AreaName { get; set; }
/// <summary>
/// 用户拥有权限访问的Controller
/// </summary>
public string ControllerName { get; set; }
/// <summary>
/// 用户拥有权限访问的Actioin
/// </summary>
public string ActionName { get; set; }
/// <summary>
/// 用户ID
/// </summary>
public dynamic[] UserKeyArray { get; set; } } /// <summary>
/// 如果没有权限返回地址
/// </summary>
public class SystemAuthorizeErrorRedirect
{
/// <summary>
/// 默认值
/// </summary>
public string DefaultUrl { get; set; } public List<SystemAuthorizeErrorRedirectItemList> ItemList { get; set; }
} public class SystemAuthorizeErrorRedirectItemList
{
/// <summary>
/// 验证类型
/// </summary>
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; } } /// <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 }
}
ASP.NET MVC权限验证 封装类的更多相关文章
- Asp.net MVC 权限验证,以及是否允许匿名访问
public class CheckUserAttribute : ActionFilterAttribute, IAuthorizationFilter { public void OnAuthor ...
- NET MVC权限验证
ASP.NET MVC权限验证 封装类 写该权限类主要目地 为了让权限配置更加的灵活,可以根据SQL.json.或者XML的方式来动态进行页面的访问控制,以及没有权限的相关跳转. 使用步骤 1.要建一 ...
- Asp.Net MVC 身份验证-Forms
Asp.Net MVC 身份验证-Forms 在MVC中对于需要登录才可以访问的页面,只需要在对应的Controller或Action上添加特性[Authorize]就可以限制非登录用户访问该页面.那 ...
- ASP.NET MVC Model验证(五)
ASP.NET MVC Model验证(五) 前言 上篇主要讲解ModelValidatorProvider 和ModelValidator两种类型的自定义实现, 然而在MVC框架中还给我们提供了其它 ...
- ASP.NET MVC Model验证(四)
ASP.NET MVC Model验证(四) 前言 本篇主要讲解ModelValidatorProvider 和ModelValidator两种类型的自定义实现,前者是Model验证提供程序,而Mod ...
- ASP.NET MVC Model验证(三)
ASP.NET MVC Model验证(三) 前言 上篇中说到在MVC框架中默认的Model验证是在哪里验证的,还讲到DefaultModelBinder类型的内部执行的示意图,让大家可以看到默认的M ...
- ASP.NET MVC Model验证(二)
ASP.NET MVC Model验证(二) 前言 上篇内容演示了一个简单的Model验证示例,然后在文中提及到Model验证在MVC框架中默认所处的位置在哪?本篇就是来解决这个问题的,并且会描述一下 ...
- ASP.NET MVC Model验证(一)
ASP.NET MVC Model验证(一) 前言 前面对于Model绑定部分作了大概的介绍,从这章开始就进入Model验证部分了,这个实际上是一个系列的Model的绑定往往都是伴随着验证的.也会在后 ...
- ASP.NET MVC 5 - 验证编辑方法(Edit method)和编辑视图(Edit view)
在本节中,您将验证电影控制器生成的编辑方法(Edit action methods)和视图.但是首先将修改点代码,使得发布日期属性(ReleaseDate)看上去更好.打开Models \ Movie ...
随机推荐
- 努力学习 HTML5 (1)—— 初体验
HTML5 代表未来:W3C ( World Wide Web Consortium, 万维网联盟) 已经放弃 XHTML,从而使 HTML5 成为正式标准并得到认可. 最简单的 HTML5 文档 & ...
- MySQL实现定时任务
如果要每30秒执行以下语句 '; 可以给MySQL建个定时任务,具体如下: delimiter // /* 设定语句终结符为 //,因存储过程语句用;结束 */ 一.查看event是否开启 show ...
- WIN7只能上QQ打不开网页,使用CMD输入netsh winsock reset
此类问题可以用腾讯电脑管家电脑诊所一键修复,请点击上方的[立即修复]即可. 附:手动修复步骤(来源:腾讯电脑管家电脑诊所,自动修复请点击上方的[立即修复])方案一:手动设置DNS(说明:如果您使用DN ...
- 解决genemotion模拟器冲突导致的Android Studio无法启动ADB的问题
首先命令行下运行 adb nodaemon server ./adb nodaemon server (Mac OSX) 如果出现错误: error: could not install *smart ...
- 【组合数学+动态规划】在如下8*6的矩阵中,请计算从A移动到B一共有____种走法。要求每次只能向上或向右移动一格,并且不能经过P。
在如下8*6的矩阵中,请计算从A移动到B一共有__种走法.要求每次只能向上或向右移动一格,并且不能经过P. A:456 B:492 C:568 D:626 E:680 F:702 解析: 8*6的矩阵 ...
- CoreImage 处理图片
1.CoreImage 滤镜的使用(马赛克模糊) CoreImage是苹果公司为了简化图片处理的难度而开发出来的类库. 随着iOS版本号升级以及硬件性能的不断提升,CoreImage将支持越来越多的滤 ...
- 【转帖】自助式BI的崛起:三张图看清商业智能和大数据分析市场趋势
自助式BI的崛起:三张图看清商业智能和大数据分析市场趋势 大数据时代,商业智能和数据分析软件市场正在经历一场巨变,那些强调易用性的,人人都能使用的分析软件正在取代传统复杂的商业智能和分析软件成为市场的 ...
- LeetCode: Unique Paths 解题报告
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The ...
- 阿里前DBA的故事
别人怎么享受生活,与你无关.你怎么磨砺与你有头.引用同事周黄江的一句话,很多人努力程度还远没有到拼天赋的时候. 成功的人都是那种目标很明确的人.对于文中厨师的经历很感兴趣.不管是IT还是餐饮,哪个行业 ...
- GitHub上排名前100的Android开源库介绍(来自github)
本项目主要对目前 GitHub 上排名前 100 的 Android 开源库进行简单的介绍,至于排名完全是根据 GitHub 搜索 Java 语言选择 (Best Match) 得到的结果,然后过滤了 ...