您现在的位置是:网站首页> 编程资料编程资料

ASP.NET MVC自定义授权过滤器_实用技巧_

2023-05-24 448人已围观

简介 ASP.NET MVC自定义授权过滤器_实用技巧_

一、授权过滤器

授权过滤器用于实现IAuthorizationFilter接口和做出关于是否执行操作方法(如执行身份验证或验证请求的属性)的安全策略。AuthorizeAttribute类继承了IAuthorizationFilter接口,是授权过滤器的示例。授权过滤器在任何其他过滤器之前运行。

如果要自定义授权过滤器,只需要定义一个类继承自AuthorizeAttribute类,然后重写AuthorizeAttribute类里面的方法即可。

二、示例

下面根据一个具体的案例来讲解如何使用自定义过滤器

1、添加对应实体类

User实体类代码如下:

using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MVCCustomerFilterDemo.Models { public class User { public int Id { get; set; } public string UserName { get; set; } public int RoleId { get; set; } } }

Role实体类代码如下:

using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MVCCustomerFilterDemo.Models { public class Role { public int Id { get; set; } public string RoleName { get; set; } public string Description { get; set; } } }

RoleWithControllerAction实体类代码如下:

using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MVCCustomerFilterDemo.Models { public class RoleWithControllerAction { public int Id { get; set; } public string ControllerName { get; set; } public string ActionName { get; set; } public string RoleIds { get; set; } } }

用于展示登录视图的登录用户实体类LogOnViewModel代码如下:

using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Web; namespace MVCCustomerFilterDemo.Models { //  /// 用户登录类 ///  public class LogOnViewModel { ///  /// 用户名 ///  [DisplayName("用户名")] public string UserName { get; set; } ///  /// 密码 ///  [DisplayName("密码")] public string Password { get; set; } ///  /// 记住我 ///  [DisplayName("记住我")] public bool RememberMe { get; set; } } }

2、添加测试数据

在程序中模拟数据库中的数据,实际使用中要去数据库查询,代码如下:

using MVCCustomerFilterDemo.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MVCCustomerFilterDemo.DataBase { ///  /// 测试数据(实际项目中,这些数据应该从数据库拿) ///  public class SampleData { public static List users; public static List roles; public static List roleWithControllerAndAction; static SampleData() { // 初始化用户 users = new List() { new User(){ Id=1, UserName="jxl", RoleId=1}, new User(){ Id=2, UserName ="senior1", RoleId=2}, new User(){ Id=3, UserName ="senior2", RoleId=2}, new User(){ Id=5, UserName="junior1", RoleId=3}, new User(){ Id=6, UserName="junior2", RoleId=3}, new User(){ Id=6, UserName="junior3", RoleId=3} }; // 初始化角色 roles = new List() { new Role() { Id=1, RoleName="管理员", Description="管理员角色"}, new Role() { Id=2, RoleName="高级会员", Description="高级会员角色"}, new Role() { Id=3, RoleName="初级会员", Description="初级会员角色"} }; // 初始化角色控制器和Action对应类 roleWithControllerAndAction = new List() { new RoleWithControllerAction(){ Id=1, ControllerName="AuthFilters", ActionName="AdminUser", RoleIds="1"}, new RoleWithControllerAction(){ Id=2, ControllerName="AuthFilters", ActionName="SeniorUser",RoleIds="1,2"}, new RoleWithControllerAction(){ Id=3, ControllerName="AuthFilters", ActionName="JuniorUser",RoleIds="1,2,3"}, new RoleWithControllerAction(){ Id=3, ControllerName="AuthFilters", ActionName="Welcome",RoleIds="1,2"}, new RoleWithControllerAction(){ Id=4, ControllerName="ActionFilters", ActionName="Index", RoleIds="2,3"}, new RoleWithControllerAction(){ Id=4, ControllerName="ActionPremisFilters", ActionName="Index", RoleIds="2,3"} }; } } }

3、新建继承类

新建一个UserAuthorize类,继承自AuthorizeAttribute类,然后F12转到定义查看AuthorizeAttribute代码,代码如下:

#region 程序集 System.Web.Mvc, Version=5.2.4.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 // E:\Practice\过滤器\自定义权限过滤器\MVCCustomerFilterDemo\packages\Microsoft.AspNet.Mvc.5.2.4\lib\net45\System.Web.Mvc.dll #endregion namespace System.Web.Mvc { // // 摘要: // 指定对控制器或操作方法的访问只限于满足授权要求的用户。 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter { // // 摘要: // 初始化 System.Web.Mvc.AuthorizeAttribute 类的新实例。 public AuthorizeAttribute(); // // 摘要: // 获取或设置有权访问控制器或操作方法的用户角色。 // // 返回结果: // 有权访问控制器或操作方法的用户角色。 public string Roles { get; set; } // // 摘要: // 获取此特性的唯一标识符。 // // 返回结果: // 此特性的唯一标识符。 public override object TypeId { get; } // // 摘要: // 获取或设置有权访问控制器或操作方法的用户。 // // 返回结果: // 有权访问控制器或操作方法的用户。 public string Users { get; set; } // // 摘要: // 在过程请求授权时调用。 // // 参数: // filterContext: // 筛选器上下文,它封装有关使用 System.Web.Mvc.AuthorizeAttribute 的信息。 // // 异常: // T:System.ArgumentNullException: // filterContext 参数为 null。 public virtual void OnAuthorization(AuthorizationContext filterContext); // // 摘要: // 重写时,提供一个入口点用于进行自定义授权检查。 // // 参数: // httpContext: // HTTP 上下文,它封装有关单个 HTTP 请求的所有 HTTP 特定的信息。 // // 返回结果: // 如果用户已经过授权,则为 true;否则为 false。 // // 异常: // T:System.ArgumentNullException: // httpContext 参数为 null。 protected virtual bool AuthorizeCore(HttpContextBase httpContext); // // 摘要: // 处理未能授权的 HTTP 请求。 // // 参数: // filterContext: // 封装有关使用 System.Web.Mvc.AuthorizeAttribute 的信息。filterContext 对象包括控制器、HTTP 上下文、请求上下文、操作结果和路由数据。 protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext); // // 摘要: // 在缓存模块请求授权时调用。 // // 参数: // httpContext: // HTTP 上下文,它封装有关单个 HTTP 请求的所有 HTTP 特定的信息。 // // 返回结果: // 对验证状态的引用。 // // 异常: // T:System.ArgumentNullException: // httpContext 参数为 null。 protected virtual HttpValidationStatus OnCacheAuthorization(HttpContextBase httpContext); } }

从AuthorizeAttribute的源代码中可以看出:里面定义了Users和Roles两个属性,只需要给这两个属性赋值,就可以控制用户或角色访问了。要实现自定义的验证只需要重写OnAuthorization和AuthorizeCore方法。所以,UserAuthorize类代码如下:

using MVCCustomerFilterDemo.DataBase; using MVCCustomerFilterDemo.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MVCCustomerFilterDemo.Extensions { public class UserAuthorize : AuthorizeAttribute { ///  /// 授权失败时呈现的视图 ///  public string AuthorizationFailView { get; set; } ///  /// 请求授权时执行 ///  public override void OnAuthorization(AuthorizationContext filterContext) { // 判断是否已经验证用户 if (!filterContext.HttpContext.User.Identity.IsAuthenticated) { // 如果没有验证则跳转到LogOn页面 filterContext.HttpContext.Response.Redirect("/Account/LogOn"); } //获得url请求里的controller和action: string strControllerName = filterContext.RouteData.Values["controller"].ToString().ToLower(); string strActionName = filterContext.RouteData.Values["action"].ToString().ToLower(); //根据请求过来的controller和action去查询可以被哪些角色操作: Models.RoleWithControllerAction roleWithControllerAction = SampleData.roleWithControllerAndAction.Find(r => r.ControllerName.ToLower() == strControllerName && r.ActionName.ToLower() == strActionName); if (roleWithControllerAction != null) { //有权限操作当前控制器和Action的角色id this.Roles = roleWithControllerAction.RoleIds; } base.OnAuthorization(filterContext); } ///  /// 自定义授权检查(返回False则授权失败) ///  protected override bool AuthorizeCore(HttpContextBase httpContext) { if (httpContext.User.Identity.IsAuthenticated) { //当前登录用户的用户名 string userName = httpContext.User.Identity.Name; //当前登录用户对象 User user = SampleData.users.Find(u => u.UserName == userName); if (user != null) { //当前登录用户的角色 Role role = SampleData.roles.Find(r => r.Id == user.RoleId); foreach (string roleid in Roles.Split(',')) { if (role.Id.ToString() == roleid) return true; } return false; } else return false; } else { //进入HandleUnauthorizedRequest return false; } } ///  /// 处理授权失败的HTTP请求 ///  protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { filterContext.Result = new ViewResult { ViewName = AuthorizationFailView }; } } }

4、添加Account控制器

Account控制器里面的LogOn方法用来显示登陆界面,控制器代码如下:

using MVCCustomerFilterDemo.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Security; namespace MVCCustomerFilterDemo.Controllers { public class AccountController : Controller { // GET: Account public ActionResult Index() { return View(); } ///  /// 显示登录视图 ///  ///  public ActionResult LogOn() { LogOnViewModel model = new LogOnViewModel(); return View(model); } ///  /// 处理用户点击登录提交回发的表单 ///  ///  ///  [HttpPost] public ActionResult LogOn(LogOnViewModel model) { //只要输入的用户名和密码一样就过 if (model.UserName.Trim() == model.Password.Trim()) { // 判断是否勾选了记住我 if (model.RememberMe) { //2880分钟有效期的cookie FormsAuthentication.SetAuth
                
                

-六神源码网