首页 > 代码库 > 自定义AuthorizeAttribute
自定义AuthorizeAttribute
/// <summary> /// 自定义AuthorizeAttribute /// </summary> public class UserAuthorizeAttribute : FilterAttribute, IAuthorizationFilter, IActionFilter { IPagePermissionManager _pagePermissionManager; IRoleManager _roleManager; IUserManager _userManager; //ICache _cache; private UserEntity _currentUser; private string _parameter; public UserAuthorizeAttribute() { this._pagePermissionManager = (IPagePermissionManager)DependencyResolver.Current.GetService(typeof(IPagePermissionManager)); this._roleManager = (IRoleManager)DependencyResolver.Current.GetService(typeof(IRoleManager)); this._userManager = (IUserManager)DependencyResolver.Current.GetService(typeof(IUserManager)); //this._cache = (ICache)DependencyResolver.Current.GetService(typeof(ICache)); } public void OnAuthorization(AuthorizationContext filterContext) { //base.OnAuthorization(filterContext); //string area = filterContext.RouteData.DataTokens["area"].ToString(); string controller = filterContext.RouteData.Values["controller"].ToString(); string action = filterContext.RouteData.Values["action"].ToString(); //验证Html.SecurityActionLink 中的操作方法 bool isCheckSecurityActionLink = false; if (filterContext.ActionDescriptor != null) { string _controller = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName; string _actionName = filterContext.ActionDescriptor.ActionName; if (_controller != controller) { controller = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName; isCheckSecurityActionLink = true; } if (_actionName != action) { action = filterContext.ActionDescriptor.ActionName; isCheckSecurityActionLink = true; } } //获取Route Url中的参数 int organizationId = 0; if (filterContext.ActionDescriptor != null && filterContext.ActionDescriptor.GetParameters() != null) { organizationId = ObjectExtensions.ToInt32(filterContext.ActionDescriptor.GetParameters().FirstOrDefault(t => t.ParameterName == "api_orgId"), 0); } //int organizationId = ObjectExtensions.ToInt32(filterContext.HttpContext.Request.QueryString["api_orgId"], 0); string path = filterContext.RequestContext.HttpContext.Server.MapPath("/Config/PagePermission.config"); string userData = http://www.mamicode.com/string.Empty; _currentUser = null; if (filterContext.HttpContext.User.Identity.IsAuthenticated) { HttpCookie authCookie = filterContext.HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);//解密 userData =http://www.mamicode.com/ authTicket.UserData; if (!string.IsNullOrEmpty(userData)) { string[] arrUserData = http://www.mamicode.com/userData.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); _currentUser = new UserEntity(); _currentUser.UserID = ObjectExtensions.ToInt32(arrUserData[0], 0); _currentUser.UserName = arrUserData[1]; _currentUser.TrueName = arrUserData[2]; _currentUser.OrganizationID = ObjectExtensions.ToInt32(arrUserData[3], 0); _currentUser.InheritFromGroup = string.Compare(arrUserData[4], "True") == 0 ? true : false; ////获取当前用户在当前页面所属模块的所有操作权限 //List<int> operateCodeList = new List<int>(); //if (!string.IsNullOrEmpty(controller) && !string.IsNullOrEmpty(action)) //{ // string pageUrl = controller + "/" + action; // int moduleId = _pagePermissionManager.GetModuleID(pageUrl); // List<PagePermission> pagePermissionList = _pagePermissionManager.GetPagePermissionList(moduleId); // foreach (PagePermission pagePermission in pagePermissionList) // { // if (!string.IsNullOrEmpty(pagePermission.PageUrl)) // { // string[] arrayPageUrl = pagePermission.PageUrl.Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries); // string controllerName = string.Empty; // string actionName = string.Empty; // if (arrayPageUrl.Length > 2) // { // controllerName = arrayPageUrl[1]; // actionName = arrayPageUrl[2]; // } // else // { // controllerName = arrayPageUrl[0]; // actionName = arrayPageUrl[1]; // } // if (!string.IsNullOrEmpty(controllerName) && !string.IsNullOrEmpty(actionName)) // { // if (this.IsAllowed(path, controllerName, actionName, organizationId)) // { // operateCodeList.Add(pagePermission.OperateCode); // } // } // } // } //} //_currentUser.OperateCodeList = operateCodeList; //获取当前用户有权限的模块权限码 _currentUser.ModuleCodeList = GetModuleCodeList(); } } } _parameter = "currentUser"; //filterContext.Controller.ViewBag.currentUser = _currentUser; bool isAllowed = this.IsAllowed(path, controller, action, organizationId); if (!isAllowed) { if (isCheckSecurityActionLink) { filterContext.Result = new ViewResult(); } else { filterContext.RequestContext.HttpContext.Response.Write("对不起,您没有权限!"); filterContext.RequestContext.HttpContext.Response.End(); } } } public void OnActionExecuted(ActionExecutedContext filterContext) { if (filterContext.HttpContext.User.Identity.IsAuthenticated) { filterContext.Controller.ViewBag.currentUser = _currentUser; } } public void OnActionExecuting(ActionExecutingContext filterContext) { if (filterContext.ActionParameters.ContainsKey(_parameter)) { filterContext.ActionParameters[_parameter] = _currentUser; } } /// <summary> /// 验证页面权限 /// </summary> /// <param name="path"></param> /// <param name="controller"></param> /// <param name="action"></param> /// <returns></returns> public bool IsAllowed(string path, string controller, string action, int organizationId) { bool isAllowed = false; if (!string.IsNullOrEmpty(controller) && !string.IsNullOrEmpty(action)) { string pageUrl = controller + "/" + action; //不检查NoCheckedPage.config 中配置的页面 string noCheckedPagePath = "/Config/NoCheckedPage.config"; List<string> noCheckedPageUrlList = XmlManager.GetAttributesValue(noCheckedPagePath, "PageUrl"); if (noCheckedPageUrlList.Contains(pageUrl)) { return true; } UserEntity userEntity = _currentUser; //用户是否登录 if (!HttpContext.Current.User.Identity.IsAuthenticated) { return false; } if (userEntity == null) { return false; } int userId = userEntity.UserID; //用户是否属于指定的部门 if (organizationId > 0) { if (organizationId != userEntity.OrganizationID) { return false; } } List<int> userRolesId = GetUserRolesId(userId, userEntity.InheritFromGroup); //超级管理员不用验证 if (userRolesId.Contains((int)SuperManagerEnum.SuperManager)) { isAllowed = true; } else { if (!string.IsNullOrEmpty(path)) { List<PagePermission> list = _pagePermissionManager.DeserializeToList<PagePermission>(path); //List<PagePermission> list = _cache.Get<List<PagePermission>>("ciwong_admin_permission_pagepermissionlist"); //if (list == null || list.Count == 0) //{ // list = _pagePermissionManager.DeserializeToList<PagePermission>(path); // _cache.Add<List<PagePermission>>("ciwong_admin_permission_pagepermissionlist", list, 1200); //} if (list.Count > 0) { //处理带空白符URL,不区分大小写 PagePermission pagePermission = list.FirstOrDefault(t => t.PageUrl.Trim().ToLower() == pageUrl.Trim().ToLower()); if (pagePermission != null) { //用户的模块权限是否被禁止 List<DisableUserPermission> disableUserPermissionList = new List<DisableUserPermission>(); disableUserPermissionList = _userManager.GetDisableUserPermission(userId, pagePermission.ModuleID, pagePermission.ModuleCode); foreach (DisableUserPermission disableUserPermission in disableUserPermissionList) { if ((pagePermission.OperateCode & disableUserPermission.OperateCode) == pagePermission.OperateCode) { return false; } } //用户是否拥有模块权限 List<Roles_ModulePermission> rolesModelPermissionList = new List<Roles_ModulePermission>(); rolesModelPermissionList = _roleManager.GetRolesModulePermission(userRolesId, pagePermission.ModuleID, pagePermission.ModuleCode); foreach (Roles_ModulePermission rolesModelPermission in rolesModelPermissionList) { if ((pagePermission.OperateCode & rolesModelPermission.OperateCode) == pagePermission.OperateCode) { isAllowed = true; } } } } } } } return isAllowed; } /// <summary> /// 获取当前用户的模块权限 /// </summary> /// <returns></returns> public List<string> GetModuleCodeList() { List<string> moduleCodeList = new List<string>(); UserEntity userEntity = _currentUser; //用户是否登录 if (!HttpContext.Current.User.Identity.IsAuthenticated) { return moduleCodeList; } if (userEntity == null) { return moduleCodeList; } int userId = userEntity.UserID; List<int> userRolesId = GetUserRolesId(userId, userEntity.InheritFromGroup); //超级管理员拥有所有模块的权限 if (userRolesId.Contains((int)SuperManagerEnum.SuperManager)) { moduleCodeList.Add("SuperManager"); } else { List<Roles_ModulePermission> rolesModulePermissionList = _roleManager.GetRolesModulePermission(userRolesId); List<DisableUserPermission> disableUserPermissionList = _userManager.GetDisableUserPermissionList(userId); if (disableUserPermissionList.Count > 0) { List<string> disableUserPermissionCode = disableUserPermissionList.Select(t => t.ModuleCode).ToList(); foreach (Roles_ModulePermission rolesModulePermission in rolesModulePermissionList) { if (!disableUserPermissionCode.Contains(rolesModulePermission.ModuleCode)) { moduleCodeList.Add(rolesModulePermission.ModuleCode); } } } else { moduleCodeList = rolesModulePermissionList.Select(t => t.ModuleCode).ToList(); } } return moduleCodeList; } private List<int> GetUserRolesId(int userId, bool inheritFromGroup) { List<int> userRolesId = new List<int>(); List<int> userGroupRolesId = new List<int>(); if (inheritFromGroup) { int groupId = _userManager.GetGroupID(userId); if (groupId > 0) { userGroupRolesId = _roleManager.GetUserGroupRoles(groupId); } //合并用户角色 userRolesId = _roleManager.GetUserRoles(userId); if (userGroupRolesId.Count > 0 && userRolesId.Count > 0) { userRolesId = userRolesId.Union(userGroupRolesId).ToList<int>(); } } else { userRolesId = _roleManager.GetUserRoles(userId); } return userRolesId; } }
自定义AuthorizeAttribute
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。