ASP.NET MVC5+EF6+EasyUI 后台管理系统(21)-权限管理系统-跑通整个系统
这一节我们来跑通整个系统,验证的流程,通过AOP切入方式,在访问方法之前,执行一个验证机制来判断是否有操作权限(如:增删改等)
原理:通过MVC自带筛选器,在筛选器分解路由的Action和controller来验证是否有权限。
首先我们要理解一下筛选器
筛选器的由来及用途
有时,您需要在调用操作方法之前或运行操作方法之后执行逻辑。
为了对此提供支持,ASP.NET MVC 提供了筛选器。 筛选器是自定义类,可提供用于向控制器操作方法添加操作前行为和操作后行为的声明性和编程性手段。
ASP.NET MVC 支持以下类型的操作筛选器:
授权筛选器。 这些筛选器用于实现 IAuthorizationFilter 和做出关于是否执行操作方法(如执行身份验证或验证请求的属性)的安全决策。 AuthorizeAttribute 类和 RequireHttpsAttribute 类是授权筛选器的示例。 授权筛选器在任何其他筛选器之前运行。
操作筛选器。 这些筛选器用于实现 IActionFilter 以及包装操作方法执行。 IActionFilter 接口声明两个方法:OnActionExecuting 和 OnActionExecuted。 OnActionExecuting 在操作方法之前运行。 OnActionExecuted 在操作方法之后运行,可以执行其他处理,如向操作方法提供额外数据、检查返回值或取消执行操作方法。
结果筛选器。 这些筛选器用于实现 IResultFilter 以及包装 ActionResult 对象的执行。 IResultFilter 声明两个方法:OnResultExecuting 和 OnResultExecuted。 OnResultExecuting 在执行 ActionResult 对象之前运行。 OnResultExecuted 在结果之后运行,可以对结果执行其他处理,如修改 HTTP 响应。 OutputCacheAttribute 类是结果筛选器的一个示例。
异常筛选器。 这些筛选器用于实现 IExceptionFilter,并在 ASP.NET MVC 管道执行期间引发了未处理的异常时执行。 异常筛选器可用于执行诸如日志记录或显示错误页之类的任务。 HandleErrorAttribute 类是异常筛选器的一个示例。
创建自定义操作筛选器
框架将先调用操作筛选器的 OnActionExecuting 方法,然后再调用以操作筛选器特性标记的任意操作方法。 同样,该框架将在操作方法完成后调用 OnActionExecuted 方法。
调用 OnResultExecuting 方法后,要立即调用您的操作返回的 ActionResult 实例。 执行结果后,紧接着就要调用 OnResultExecuted 方法。 这些方法对于执行日志记录、缓存输出结果之类的操作非常有用。
以上都是理论问题了,说到底我们就是要OnActionExecuting利用这个方法
当一个Action被执行时调用OnActionExecuting判断是否有权限操作。
由于OnActionExecuting涉及到其他用户和权限的访问我们需要添加SysUser和SysRight的BLL和DAL层了
我们还需要一个存储过程[P_Sys_GetRightOperate]用于取模块的当前用户操作权限,这里为什么用存储过程呢,快点呗,反正这快不用怎么维护了
存储过程如下:
USE db
GO /****** Object: StoredProcedure [dbo].[P_Sys_GetRightOperate] Script Date: 12/01/2013 12:25:48 ******/
SET ANSI_NULLS ON
GO SET QUOTED_IDENTIFIER ON
GO -- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[P_Sys_GetRightOperate]
@userId varchar(50),@url varchar(200)
AS
--取模块的当前用户操作权限
select distinct KeyCode,IsValid from SysRightOperate where RightId in(
select a.id from SysRight a, SysModule b where RoleId in(
select SysRoleId from SysRoleSysUser where SysUserId =@userId)
and a.ModuleId = b.Id
and b.Url =@url)
and IsValid=1 GO
创建好了把存储过程更新到EF中去,EF5.0将自动创建一个复杂的类型,大家可以打开来看下
创建一个权限的类permModel,我们将获取到的权限保存到这个类中去,这个类最终是一个一个的session转换而来的。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace App.Models.Sys
{
public class permModel
{
public string KeyCode { get; set; }//操作码
public bool IsValid { get; set; }//是否验证
}
}
SysUser的BLL层和SysRight的DAL层了,如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using App.Models;
using App.Models.Sys; namespace App.IDAL
{
public interface ISysRightRepository
{
List<permModel> GetPermission(string accountid, string controller);
}
}
ISysRightRepository
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using App.IDAL;
using App.Models;
using App.Models.Sys; namespace App.DAL
{
public class SysRightRepository : ISysRightRepository,IDisposable
{ /// <summary>
/// 取角色模块的操作权限,用于权限控制
/// </summary>
/// <param name="accountid">acount Id</param>
/// <param name="controller">url</param>
/// <returns></returns>
public List<permModel> GetPermission(string accountid, string controller)
{ using (DBContainer db = new DBContainer())
{
List<permModel> rights = (from r in db.P_Sys_GetRightOperate(accountid, controller)
select new permModel
{
KeyCode = r.KeyCode,
IsValid = r.IsValid
}).ToList();
return rights;
}
}
public void Dispose()
{ }
}
}
SysRightRepository
GetPermission将通过存储过程访问取得数据
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using App.Models.Sys;
using App.Common;
using App.Models; namespace App.IBLL
{
public interface ISysUserBLL
{
List<permModel> GetPermission(string accountid, string controller); }
}
ISysUserBLL
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using App.BLL.Core;
using App.IBLL;
using Microsoft.Practices.Unity;
using App.IDAL;
using App.Models.Sys;
using App.Common;
using App.Models;
using System.Transactions;
namespace App.BLL
{
public class SysUserBLL : BaseBLL, ISysUserBLL
{
[Dependency]
public ISysRightRepository sysRightRepository { get; set; }
public List<permModel> GetPermission(string accountid, string controller)
{
return sysRightRepository.GetPermission(accountid,controller);
} }
}
SysUserBLL
可以把SysRightRepository变成SysUserRepository层,我这样做是为了区分一下而已,SysRight代表权限,SysUser是用户,根据不同的用户获取他的权限
我们创建一个筛选器在App.Admin下的Core创建SupportFilter.cs
添加如下代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using App.Models.Sys;
using App.BLL;
using App.DAL; namespace App.Admin
{
public class SupportFilterAttribute : ActionFilterAttribute
{
public string ActionName { get; set; }
private string Area;
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext); }
/// <summary>
/// Action加上[SupportFilter]在执行actin之前执行以下代码,通过[SupportFilter(ActionName="Index")]指定参数
/// </summary>
/// <param name="filterContext">页面传过来的上下文</param>
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//读取请求上下文中的Controller,Action,Id
var routes = new RouteCollection();
RouteConfig.RegisterRoutes(routes);
RouteData routeData = routes.GetRouteData(filterContext.HttpContext);
//取出区域的控制器Action,id
string ctlName = filterContext.Controller.ToString();
string[] routeInfo = ctlName.Split('.');
string controller = null;
string action = null;
string id = null; int iAreas = Array.IndexOf(routeInfo, "Areas");
if (iAreas > )
{
//取区域及控制器
Area = routeInfo[iAreas + ];
}
int ctlIndex = Array.IndexOf(routeInfo, "Controllers");
ctlIndex++;
controller = routeInfo[ctlIndex].Replace("Controller", "").ToLower(); string url = HttpContext.Current.Request.Url.ToString().ToLower();
string[] urlArray = url.Split('/');
int urlCtlIndex = Array.IndexOf(urlArray, controller);
urlCtlIndex++;
if (urlArray.Count() > urlCtlIndex)
{
action = urlArray[urlCtlIndex];
}
urlCtlIndex++;
if (urlArray.Count() > urlCtlIndex)
{
id = urlArray[urlCtlIndex];
}
//url
action = string.IsNullOrEmpty(action) ? "Index" : action;
int actionIndex = action.IndexOf("?", );
if (actionIndex > )
{
action = action.Substring(, actionIndex);
}
id = string.IsNullOrEmpty(id) ? "" : id; //URL路径
string filePath = HttpContext.Current.Request.FilePath;
AccountModel account = filterContext.HttpContext.Session["Account"] as AccountModel;
if (ValiddatePermission(account, controller, action, filePath))
{
return;
}
else
{
filterContext.Result = new EmptyResult();
return;
}
}
public bool ValiddatePermission(AccountModel account, string controller, string action, string filePath)
{
bool bResult = false;
string actionName = string.IsNullOrEmpty(ActionName) ? action : ActionName;
if (account != null)
{
List<permModel> perm = null;
//测试当前controller是否已赋权限值,如果没有从
//如果存在区域,Seesion保存(区域+控制器)
if (!string.IsNullOrEmpty(Area))
{
controller = Area + "/" + controller;
}
perm = (List<permModel>)HttpContext.Current.Session[filePath];
if (perm == null)
{
using (SysUserBLL userBLL = new SysUserBLL()
{
sysRightRepository = new SysRightRepository()
})
{
perm = userBLL.GetPermission(account.Id, controller);//获取当前用户的权限列表
HttpContext.Current.Session[filePath] = perm;//获取的劝降放入会话由Controller调用
}
}
//当用户访问index时,只要权限>0就可以访问
if (actionName.ToLower() == "index")
{
if (perm.Count > )
{
return true;
}
}
//查询当前Action 是否有操作权限,大于0表示有,否则没有
int count = perm.Where(a => a.KeyCode.ToLower() == actionName.ToLower()).Count();
if (count > )
{
bResult = true;
}
else
{
bResult = false;
HttpContext.Current.Response.Write("你没有操作权限,请联系管理员!");
} }
return bResult;
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
base.OnResultExecuted(filterContext);
}
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
base.OnResultExecuting(filterContext);
}
} }
这是一个筛选器。所有逻辑代码都在这里了
打开SysSampleController
修改Create方法变为以下
[SupportFilter]
public ActionResult Create()
{
return View();
}
回到筛选器public string ActionName { get; set; },其中ActionName是自定义Action的名称,比如在Create中直接[SupportFilter]那么ActionName取得就是Create,这将和你的数据库操作码进行对应的,那么我的方法是CreateAttr,那么要使用Create这个操作码,怎么办
那么就是
[SupportFilter(ActionName = "Create")]
public ActionResult CreateAttr()
那么类似的写法
[SupportFilter(ActionName = "Index")]
public JsonResult GetList()
Index无需填写操作码将自动创建操作码,如果你拥有一个操作码那么index将被授权,这个是我们与系统之间的一个约定(你可以去掉这个约定,修改代码即可)
假如你拥有增删改权限却没有访问列表的权限,那不是...
OnActionExecuting负责分解,交给ValiddatePermission去生成权限
如果写在Areas区域的也是兼容的,已经做了处理。
如果你越权操作那么将执行 HttpContext.Current.Response.Write("你没有操作权限,请联系管理员!");
目前位置我们已经跑通了整个系统了,接下来就是自动化的用户角色之间的授权和模块的制作了,能跑通,其他都是很简单了,对吧
这一章比较复杂,需要对AOP编程,MVC的筛选器,和路由进行了解,才能读的比较顺。
如果你没有读懂,那么代码敲一遍,那么你也就差不多知道了
代码进行了大量的注释,还不懂那么留言。
目前为止,我们一个基于按钮级别的权限系统已经全部跑通,现在,可以创建一些没有权限的Action来验证了
我创建:(很明显我们数据库没有这个test的 action的权限),所以你别想越权操作了
[SupportFilter]
public ActionResult Test()
{
return View();
}
最后预览
我们预览一个有权限的
感谢大家,花了你宝贵的时间阅读这一节。
ASP.NET MVC5+EF6+EasyUI 后台管理系统(21)-权限管理系统-跑通整个系统的更多相关文章
- ASP.NET MVC5+EF6+EasyUI 后台管理系统(1)-前言与目录(持续更新中...)
开发工具:VS2015(2012以上)+SQL2008R2以上数据库 您可以有偿获取一份最新源码联系QQ:729994997 价格 666RMB 升级后界面效果如下: 任务调度系统界面 http: ...
- ASP.NET MVC5+EF6+EasyUI 后台管理系统(1)-前言与目录(转)
开发工具:VS2015(2012以上)+SQL2008R2以上数据库 您可以有偿获取一份最新源码联系QQ:729994997 价格 666RMB 升级后界面效果如下: 日程管理 http://ww ...
- ASP.NET MVC5+EF6+EasyUI 后台管理系统(63)-Excel导入和导出-自定义表模导入
系列目录 前言 上一节使用了LinqToExcel和CloseXML对Excel表进行导入和导出的简单操作,大家可以跳转到上一节查看: ASP.NET MVC5+EF6+EasyUI 后台管理系统(6 ...
- ASP.NET MVC5+EF6+EasyUI 后台管理系统-WebApi的用法与调试
1:ASP.NET MVC5+EF6+EasyUI 后台管理系统(1)-WebApi与Unity注入 使用Unity是为了使用我们后台的BLL和DAL层 2:ASP.NET MVC5+EF6+Easy ...
- ASP.NET MVC5+EF6+EasyUI 后台管理系统(51)-系统升级
系统很久没有更新内容了,期待已久的更新在今天发布了,最近花了2个月的时间每天一点点,从原有系统 MVC4+EF5+UNITY2.X+Quartz 2.0+easyui 1.3.4无缝接入 MVC5+E ...
- ASP.NET MVC5+EF6+EasyUI 后台管理系统(58)-DAL层重构
系列目录 前言:这是对本文系统一次重要的革新,很久就想要重构数据访问层了,数据访问层重复代码太多.主要集中增删该查每个模块都有,所以本次是为封装相同接口方法 如果你想了解怎么重构普通的接口DAL层请查 ...
- ASP.NET MVC5+EF6+EasyUI 后台管理系统(34)-文章发布系统①-简要分析
系列目录 最新比较闲,为了学习下Android的开发构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(1)-前言与,虽然有点没有目的的学习,但还是了解了Andro ...
- ASP.NET MVC5+EF6+EasyUI 后台管理系统(54)-工作流设计-所有流程监控
系列目录 先补充一个平面化登陆页面代码,自己更换喜欢的颜色背景 @using Apps.Common; @{ Layout = null; } <!DOCTYPE html> <ht ...
- ASP.NET MVC5+EF6+EasyUI 后台管理系统(56)-插件---单文件上传与easyui使用fancybox
系列目录 https://yunpan.cn/cZVeSJ33XSHKZ 访问密码 0fc2 今天整合lightbox插件Fancybox1.3.4,发现1.3.4版本太老了.而目前easyui 1 ...
随机推荐
- 理解CSS边框border
前面的话 边框是CSS盒模型属性中默默无闻的一个普通属性,CSS3的到来,但得边框属性重新焕发了光彩.本文将详细介绍CSS边框 基础样式 边框是一条以空格分隔的集合样式,包括边框粗细(边框宽度 ...
- 在.NET Core 里使用 BouncyCastle 的DES加密算法
.NET Core上面的DES等加密算法要等到1.2 才支持,我们可是急需这个算法的支持,文章<使用 JavaScriptService 在.NET Core 里实现DES加密算法>需要用 ...
- POCO Controller 你这么厉害,ASP.NET vNext 知道吗?
写在前面 阅读目录: POCO 是什么? 为什么会有 POJO? POJO 的意义 POJO 与 PO.VO 的区别 POJO 的扩展 POCO VS DTO Controller 是什么? 关于 P ...
- Centos6.5下编译安装mysql 5.6
一:卸载旧版本 使用下面的命令检查是否安装有MySQL Server rpm -qa | grep mysql 有的话通过下面的命令来卸载掉 rpm -e mysql //普通删除模式 rpm -e ...
- 【WCF】自定义错误处理(IErrorHandler接口的用法)
当被调用的服务操作发生异常时,可以直接把异常的原始内容传回给客户端.在WCF中,服务器传回客户端的异常,通常会使用 FaultException,该异常由这么几个东东组成: 1.Action:在服务调 ...
- 如何快速优化手游性能问题?从UGUI优化说起
WeTest 导读 本文作者从自身多年的Unity项目UI开发及优化的经验出发,从UGUI,CPU,GPU以及unity特有资源等几个维度,介绍了unity手游性能优化的一些方法. 在之前的文 ...
- 缓存工厂之Redis缓存
这几天没有按照计划分享技术博文,主要是去医院了,这里一想到在医院经历的种种,我真的有话要说:医院里的医务人员曾经被吹捧为美丽+和蔼+可亲的天使,在经受5天左右相互接触后不得不让感慨:遇见的有些人员在挂 ...
- input标签中button在iPhone中圆角的问题
1.问题 使用H5编写微信页面时,使用<input type="button"/>时,在Android手机中显示正常,但是在iPhone手机中则显示不正常,显示为圆角样 ...
- 【腾讯Bugly干货分享】Android Linker 与 SO 加壳技术
本文来自于腾讯bugly开发者社区,非经作者同意,请勿转载,原文地址:http://dev.qq.com/topic/57e3a3bc42eb88da6d4be143 作者:王赛 1. 前言 Andr ...
- EC笔记:第4部分:20、传递引用代替传值
考虑以下场景: #include <iostream> #include <string> using namespace std; struct Person { strin ...