在上一节中提到可以使用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
相关推荐
通过重写AuthorizeAttribute实现对不同控制器的访问权限,比较简单的一个,你也可以加上自己的一些内容
MVC自定义权限控制示例代码,一个小样例,通过继承MVC框架中的AuthorizeAttribute来自定义权限。
ASP.NET mvc5 用过滤器验证用户登录与否,没登录则跳登录页面
AuthorizeAttribute扩展 AuthorizeAttribute Extended基于身份验证和/或授权结果将403... 必须using别名来避免System.Web.Mvc.AuthorizeAttribute类的混淆。 using AuthorizeAttribute = Aliencube . AuthorizeAtt
C# MVC 过滤器防止SQL注入
NHibernate+MVC4+bootstrap+Redis+T4 权限管理 思路是:扩展AuthorizeAttribute,在Controller里面标识类或方法,来获取档期url地址 判断是否合法访问
扩展MVC AuthorizeAttribute的行为以进行基于活动的授权
webapi重写Authorize的HandleUnauthorizedRequest,让服务端返回json,并且把401改为其他状态码来避免被重定向
1.权限控制使用controller和 action来实现,权限方式有很多种,最近开发项目使用控制控制器方式实现代码如下 /// /// 用户权限控制 /// public class UserAuthorize : AuthorizeAttribute { /// /// 授权失败...
为了实现保持登录状态,可以用cookie来解决这一问题 假设过期时间为30分钟,校验发生在服务器,借助过滤器,可以这样写 public class PowerFilter : AuthorizeAttribute { public override void OnAuthorization...
项目中经常需要使用WebAPI编写接口提供给其他人调用, 那么接口就需要进行身份验证,否则只要知道了这个接口的地址都可以访问了 ...主要通过重新AuthorizeAttribute内OnAuthorization方法进行身份验证
主要介绍了.Net Core 权限验证与授权(AuthorizeFilter、ActionFilterAttribute),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
一、用户 二、用户组 2.1浏览用户组 在开始做浏览用户组之前,首先要考虑权限问题。...因为管理员这块的功能还没做,目的是不验证管理员就可以进行添加、删除、浏览,权限验证代码等以后写管理员这块时
使用visual studio 2019 创建的 asp...startup类中注册使用Authentication和Authorization中间件服务,在controller或action中使用AuthorizeAttribute和AllowAnonymousAttribute控制访问权限。 详见代码,都有注释。
1.用.Net6平台WebApi项目开发 2.使用jwt给用户颁发密钥 3.swagger验证配置 4.接口jwt验证密钥方法 5.运行就能使用
CursoNETCore3.1:NETCore 3.1.NET5.0- C#+ Arquitetura DDD + Entity Framework Core com MySQL + Swagger + AutoMapper + JWT令牌
.RequireAuthorization(new AuthorizeAttribute { Roles = "Administrator"}) .EnableGrpcWeb(); 我还添加了一个Client / 页面,其中包含当前用户的声明列表。 它使用Kestrel作为默认Web服务器,SQLite数据库,...
一、MVC和WebApi路由机制比较 ........................................................................................................................................ 5 1、MVC里面的路由 ...................