续接上篇:Asp.Net MVC 权限控制(一):使用 Authorize Roles 简单实现
由于直接在Controller上标记角色名有很大的局限性,所以本示例使用 ActionFilterAttribute 进行权限拦截。
首先创建三类标记:
1. 匿名访问标记(AnonymousAttribute)
2. 登录用户访问标记(LoginAllowViewAttribute)
3. 权限验证访问标记(PermissionPageAttribute)
最重要的一个权限拦截:AuthorizeFilter,包括三步验证:
1. 是否为匿名访问,如果是匿名访问直接通过;
2. 是否为权限验证,通过查询登录时保存的Cookie进行验证;
3. 是否已登录,如果登录直接通过;
/// <summary> /// 权限拦截 /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)] public class AuthorizeFilter : ActionFilterAttribute { /// <summary> /// 在执行操作方法之前由 ASP.NET MVC 框架调用。 /// </summary> /// <param name="filterContext"></param> public override void OnActionExecuting(ActionExecutingContext filterContext) { //根据验证判断进行处理 if (!this.AuthorizeCore(filterContext)) { filterContext.RequestContext.HttpContext.Response.Redirect("~/Account/Login"); } } /// <summary> /// //权限判断业务逻辑 /// </summary> /// <param name="filterContext"></param> /// <param name="isViewPage">是否是页面</param> /// <returns></returns> protected virtual bool AuthorizeCore(ActionExecutingContext filterContext) { object[] filter; // 验证当前Action是否是匿名访问Action filter = filterContext.Controller.GetType().GetCustomAttributes(typeof(AnonymousAttribute), true); if (filter.Length == 1) { return true; } // 验证当前Action是否是权限控制页面Action filter = filterContext.Controller.GetType().GetCustomAttributes(typeof(PermissionPageAttribute), true); if (filter.Length == 1) { //获取 controllerName 名称 var controllerName = filterContext.RouteData.Values["controller"].ToString(); //获取ACTION 名称 var actionName = filterContext.RouteData.Values["action"].ToString(); var validateAuthorize = new ValidateAuthorize(); return validateAuthorize.validate(controllerName); } // 验证当前Action是否是登录用户Action filter = filterContext.Controller.GetType().GetCustomAttributes(typeof(LoginAllowViewAttribute), true); if (filter.Length == 1) { return HttpContext.Current.User.Identity.IsAuthenticated; } throw new Exception("用户验证出错!"); } }
用户登录后保存用户信息。
[HttpPost] [ValidateAntiForgeryToken] public ActionResult Login(LoginModel model, string returnUrl) { string UserData = ""; var userName = model.UserName; if (userName == "admin") { UserData = "Log"; } else if (userName == "in") { UserData = "Infrastructure"; } else if (userName == "fl") { UserData = "FileLibrary"; } FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket( 1, userName, DateTime.Now, DateTime.Now.AddMinutes(20), false, UserData//写入用户角色 ); string encryptedTicket = FormsAuthentication.Encrypt(authTicket); System.Web.HttpCookie authCookie = new System.Web.HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); System.Web.HttpContext.Current.Response.Cookies.Add(authCookie); return RedirectToAction("Index", "Home"); }
Asp.Net MVC 权限控制(二):Controller级别控制,布布扣,bubuko.com
时间: 2024-10-11 10:22:58