随笔- 28  文章- 31  评论- 16

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 == )
{
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文件即可

使用时,只需要在Global.asax中注册该filter

filters.Add(new CustomAuthorizeAttribute());

当然这只是一个简单的例子,实际应用中会复杂许多,还可能要实现在即的MemberShipProvider和RoleProvider

C#_MVC 自定义AuthorizeAttribute实现权限管理的更多相关文章

  1. MVC自定义AuthorizeAttribute实现权限管理

    [转]MVC自定义AuthorizeAttribute实现权限管理 原文载自:小飞的DD http://www.cnblogs.com/feiDD/articles/2844447.html 网站的权 ...

  2. MVC 自定义AuthorizeAttribute实现权限管理

    在上一节中提到可以使用AuthorizeAttribute进行权限管理: [Authorize] public ActionResult TestAuthorize() { return View() ...

  3. SharePoint _layouts下自定义程序页面权限管理

    在sharepoint中,_layouts下的自定义页面没有特别的权限,只要用户能访问sharepoint站点就可以访问_layouts下的自定义程序页面,现在我们需要给自定义页面做一下权限认证.要求 ...

  4. MVC 自定义AuthorizeAttribute 实现权限验证

    MVC内置的AuthorizeFilter先于Action/Result过滤器执行,为网站权限验证提供了很好的一套验证机制. 通过自定义的AuthorizeAttribute可以实现对用户权限的验证. ...

  5. 玩一玩基于Token的 自定义身份认证+权限管理

    使用基于 Token 的身份验证方法,在服务端不需要存储用户的登录记录.大概的流程是这样的: 客户端使用用户名跟密码请求登录 服务端收到请求,去验证用户名与密码 验证成功后,服务端会签发一个 Toke ...

  6. 自定义Spring Security权限控制管理(实战篇)

    上篇<话说Spring Security权限管理(源码)>介绍了Spring Security权限控制管理的源码及实现,然而某些情况下,它默认的实现并不能满足我们项目的实际需求,有时候需要 ...

  7. 权限管理(java+struts2(自定义标签)实现)--------->全代码演示

    地址:http://blog.chinaunix.net/uid-24343152-id-3673026.html 最近由于项目不是很紧所以总结了之前做了n遍的权限管理功能.以便之后系统copy之用. ...

  8. 潭州课堂25班:Ph201805201 django框架 第十三课 自定义404页面,auth系统中的User模型,auth系统权限管理 (课堂笔记)

    当 DEBUG=True 时,django 内部的404报错信息, 自带的报错信息, 要自定义404信息,要先把 DEBUG=False , 之后要自定义4040页面,有两种方法, 方法1,在创建40 ...

  9. DRF内置权限组件之自定义权限管理类

    DRF内置权限组件permissions 权限控制可以限制用户对于视图的访问和对于具体数据对象的访问. 在执行视图的dispatch()方法前,会先进行视图访问权限的判断 在通过get_object( ...

随机推荐

  1. hdu 3367 Pseudoforest

    Pseudoforest Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others) To ...

  2. Erlang之IO编程

    Erlang用于操纵文件I/O的模块有:file模块:打开.读.写.关闭文件已经操作目录的方法基本都在这里 filename模块:提供平台独立方式用于操纵文件名 filelib模块:file模块的扩展 ...

  3. jdk1.6新特性

    1.Web服务元数据 Java 里的Web服务元数据跟微软的方案基本没有语义上的区别,自从JDK5添加了元数据功能(Annotation)之后,SUN几乎重构了整个J2EE体 系, 由于变化很大,干脆 ...

  4. 2、Android应用程序基本特性

    1. apk是android应用程序安装格式,.dex是Android二进制执行文件格式. 2.Android操作系统是基于Linux的多用户操作系统,每一个应用程序都是使用的不同的用户. 3. 默认 ...

  5. android studio 使用的一些注意,一些报错的解决方法(原创)

    NDK 编译无法通过 注意看 build.gradle 里面的 有些是 ndk-build windows 上用 ndk-build.cmd Summary: gradle calls ndk-bui ...

  6. linux内核-双向链表

    linux中的经典宏定义 offsetof 定义:offsetof在linux内核的include/linux/stddef.h中定义. #define offsetof(TYPE, MEMBER) ...

  7. IO_REMOVE_LOCK使用方法小结(转载加改正)

    原文链接:http://www.programlife.net/io_remove_lock.html IO_REMOVE_LOCK(删除锁)的具体结构没有公开,WDK的文档中中查不到IO_REMOV ...

  8. hbase0.96与hive0.12整合高可靠文档及问题总结

    本文链接:http://www.aboutyun.com/thread-7881-1-1.html 问题导读:1.hive安装是否需要安装mysql?2.hive是否分为客户端和服务器端?3.hive ...

  9. AVD Snapshot功能

    写程序的时候,经常会碰到:The application has stopped unexpectly… 有时候,会想对原来软件增加新功能或者修改bug.在eclipse修改后保存代码(注意,要保存所 ...

  10. AVLTree的节点删除

    当年实现自己的共享内存模板的时候,map和set的没有实现,本来考虑用一个AVLTree作为底层实现的,为啥,因为我当时的数据结构知识里面我和RBTree不熟,只搞过AVLTree,但当时我一直没有看 ...