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 ...
随机推荐
- 【AR实验室】ARToolKit之Example篇
0x00 - 前言 PS : 我突然意识到ARToolKit本质可能就是一个可以实时求解相机内外参的解决方案. 拿到一个新的SDK,90%的人应该都会先跑一下Example.拿到ARToolKit的S ...
- nginx+iis+redis+Task.MainForm构建分布式架构 之 (redis存储分布式共享的session及共享session运作流程)
本次要分享的是利用windows+nginx+iis+redis+Task.MainForm组建分布式架构,上一篇分享文章制作是在windows上使用的nginx,一般正式发布的时候是在linux来配 ...
- J a v a 的“多重继承”
接口只是比抽象类“更纯”的一种形式.它的用途并不止那些.由于接口根本没有具体的实施细节——也就是说,没有与存储空间与“接口”关联在一起——所以没有任何办法可以防止多个接口合并到一起.这一点是至关重要的 ...
- addTwoNumbers
大神的代码好短,自己写的120多行=_= 各种判断 ListNode *f(ListNode *l1, ListNode *l2) { ListNode *p1 = l1; ListNode *p2 ...
- 纯javaScript、jQuery实现个性化图片轮播
纯javaScript实现个性化图片轮播 轮播原理说明<如上图所示>: 1. 画布部分(可视区域)属性说明:overflow:hidden使得超出画布部分隐藏或说不可见.position: ...
- android计算每个目录剩余空间丶总空间以及SD卡剩余空间
ublic class MemorySpaceCheck { /** * 计算剩余空间 * @param path * @return */ public static String getAvail ...
- 一个标签的72变,打造一个纯CSS图标库
每次要用到图标的时候都会到 icono 去copypaste,但每次用到的时候尺寸都各不一样,总是要调整参数,巨烦.当然你可以会想到用zoom.scale来做缩放,但是这样的缩放会使得线宽也变粗了,不 ...
- Linux网络编程-tcp缓存设置
最近发现服务的逻辑完成时间很短,但是上游接收到的时间比较长,所以就怀疑是底层数据的序列化/反序列化.读写.传输有问题,然后怀疑是TCP的读写缓存是不是设置太小.现在就记录下TCP缓存的各配置项以及缓存 ...
- MySQL基础之索引
这段时间看了好多东西却没有总结,今天在这里写一写 关于索引 索引是一种提高查询效率的方法,它是B+树的结构,从根到中间节点在到叶子节点,无需遍历全部就可以查到所需的东西 关于索引的创建 一般有俩种方式 ...
- FastCgi与PHP-fpm之间的关系
web server(比如说nginx)只是内容的分发者.比如,如果请求/index.html,那么web server会去文件系统中找到这个文件,发送给浏览器,这里分发的是静态数据.好了,如果现在请 ...