MVC 自定义AuthorizeAttribute实现权限管理
来源:互联网 发布:机顶盒桌面软件 编辑:程序博客网 时间:2024/04/29 21:02
MVC中AuthorizeAttribute用法并实现授权管理
(2015-01-05 13:49:30)authorizeattribute
handleunauthorized
authorizecore
分类: MVC
1.创建一个类(用来检查用户是否登录和用户权限)代码如下:
2.页面程序,也就是控制器里的程序,如下
//MemberCheck是扩展特性,自定义特性名称是根据上面的类MemberCheckAttribute名进行变化
//当访问/user/index时,程序会先走自定义特性MemberCheck然后再走Index
[MemberCheck]
public class UserController : Controller
{
}
MVC 自定义AuthorizeAttribute实现权限管理
在上一节中提到可以使用AuthorizeAttribute进行权限管理:
[Authorize] public ActionResult TestAuthorize() { return View(); } [Authorize(Users="test1,test2")] public ActionResult TestAuthorize() { return View(); } [Authorize(Roles="Admin")] public ActionResult TestAuthorize() { return View(); }
但是通常情况下,网站的权限并不是固定不变的,当新增角色或者角色改变时,只能修改每个Action对应的特性,当项目较大时工作量可想而知。幸运的是我们可以重写AuthorizeAttribute达到自定义的权限管理。新建一个CustomAuthorizeAttribute类,使这个类继承于AuthorizeAttribute。打开AuthorizeAttribute查看下方法说明,我们只需要重写AuthorizeCore和OnAuthorization就能达到我们的目的。
// Summary: // When overridden, provides an entry point for custom authorization checks. // // Parameters: // httpContext: // The HTTP context, which encapsulates all HTTP-specific information about // an individual HTTP request. // // Returns: // true if the user is authorized; otherwise, false. // // Exceptions: // System.ArgumentNullException: // The httpContext parameter is null. protected virtual bool AuthorizeCore(HttpContextBase httpContext);// // Summary: // Called when a process requests authorization. // // Parameters: // filterContext: // The filter context, which encapsulates information for using System.Web.Mvc.AuthorizeAttribute. // // Exceptions: // System.ArgumentNullException: // The filterContext parameter is null. public virtual void OnAuthorization(AuthorizationContext filterContext);
在CustomAuthorizeAttribute中重载AuthorizeCore方法,它的处理逻辑如下:首先判断当前账户是否被认证,如果没有,则返回false;然后获取当前账户的类型,并跟给定的类型进行比较,如果类型相同,则返回true,否则返回false。一般网站中权限管理都会使用权限树,然后将角色的权限保存至数据库或者文件中,本例中我们使用XML文件保存每个Action的角色,这样在用户请求Action时,由XML文件获取Action对应的权限,然后检测账户是否有相应的权限。CustomAuthorizeAttribute类的代码如下:
public class CustomAuthorizeAttribute : System.Web.Mvc.AuthorizeAttribute { public new string[] Roles { get; set; } protected override bool AuthorizeCore(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("HttpContext"); } if (!httpContext.User.Identity.IsAuthenticated) { return false; } if (Roles == null) { return true; } if (Roles.Length == 0) { return true; } if (Roles.Any(httpContext.User.IsInRole)) { return true; } return false; } public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext) { string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = filterContext.ActionDescriptor.ActionName; string roles = GetRoles.GetActionRoles(actionName, controllerName); if (!string.IsNullOrWhiteSpace(roles)) { this.Roles = roles.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); } base.OnAuthorization(filterContext); } }
当用户请求一个Action时,会调用OnAuthorization方法,该方法中GetRoles.GetActionRoles(actionName, controllerName);根据Controller和Action去查找当前Action需要具有的角色类型,获得Action的Roles以后,在AuthorizeCore中与用户的角色进行比对Roles.Any(httpContext.User.IsInRole),如果没有相应权限则返回false,程序就会自动跳转到登录页面。
GetRoles为XML解析类,代码如下:
public class GetRoles { public static string GetActionRoles(string action, string controller) { XElement rootElement = XElement.Load(HttpContext.Current.Server.MapPath("/")+"ActionRoles.xml"); XElement controllerElement = findElementByAttribute(rootElement, "Controller", controller); if (controllerElement != null) { XElement actionElement = findElementByAttribute(controllerElement, "Action", action); if (actionElement != null) { return actionElement.Value; } } return ""; } public static XElement findElementByAttribute(XElement xElement,string tagName, string attribute) { return xElement.Elements(tagName).FirstOrDefault(x => x.Attribute("name").Value.Equals(attribute,StringComparison.OrdinalIgnoreCase)); } }
相应的权限XMl文件:
<?xml version="1.0" encoding="utf-8" ?><Roles> <Controller name="Home"> <Action name="Index"></Action> <Action name="About">Manager,Admin</Action> <Action name="Contact">Admin</Action> </Controller></Roles>
当需求发生变化时,只需要修改XML文件即可
使用时,只需要在FilterConfig中注册该filter
filters.Add(new CustomAuthorizeAttribute());
当然这只是一个简单的例子,实际应用中会复杂许多,还可能要实现在即的MemberShipProvider和RoleProvider
»下一篇:MVC Area领域处理以及T4MVC的使用
filters.Add(new CustomAuthorizeAttribute());
================
楼主这个在哪里注册的?
这个我也没找到方法,但可以在要使用的Controller里引用一下“CustomAuthorizeAttribute ”的命名空间也行;
filters.Add(new CustomAuthorizeAttribute());
请问楼主怎么实现?
- MVC 自定义AuthorizeAttribute实现权限管理
- mvc 3.0 自定义 AuthorizeAttribute 权限管理
- MVC自定义AuthorizeAttribute管理页面浏览权限
- c# mvc 自定义AuthorizeAttribute
- MVC用户权限管理AuthorizeAttribute
- MVC 基于 AuthorizeAttribute 实现的登陆权限控制
- 重写AuthorizeAttribute实现自己的权限验证
- 重写AuthorizeAttribute实现自己的权限验证
- 自定义AuthorizeAttribute
- 解决自定义AuthorizeAttribute实现授权管理,AllowAnonymous属性失效导致无法匿名访问控制器的问题
- ASP.NET MVC实现权限管理以及权限分配
- MVC特性认证 AuthorizeAttribute 类
- MVC特性认证 AuthorizeAttribute 类
- MVC中使用AuthorizeAttribute身份验证
- 自定义拦截器实现权限管理
- django认证系统实现自定义权限管理
- AuthorizeAttribute
- spring mvc +hibernate +spring +shiro 实现权限管理详细配置
- Intent的应用嘞
- 内网linux 6.5 搭建一个搭建无人执守安装服务器
- 采用gitolite架设git服务器
- Android 蓝牙开发基本流程
- UVA 1395 Slim Span
- MVC 自定义AuthorizeAttribute实现权限管理
- Linux系统备份与恢复--概述
- solr-数据库导入
- Ubuntu12.04-git的安装
- 生产者与消费者小例子
- 文件切割与合并
- 给刚出道的游戏开发人员的几点忠告
- error could not create the java virtual machine.error:a fatal exception has occurred...问题之解决
- UVA 1151 Buy or Build
重写 AuthorizeCore OnAuthorization 后我在我用验证权限的类继承类A
我要启用权限在上面加
[Authorize(Roles=???)] 这个怎么写啊 !
还有新建一个类的时候CustomAuthorizeAttribute 我看网上的都加了这个后缀Attribute 不加不行吗 也没看到为什么的原因 呵呵!