首页 > 代码库 > 自定义权限验证特性

自定义权限验证特性

/// <summary>
    /// 判断是否有权限操作
    /// </summary>
    public class RightAuthorizeAttribute : AuthorizeAttribute
    {
        /// <summary>
        /// actionName
        /// </summary>
        private string _actionName;

        /// <summary>
        /// controllerName
        /// </summary>
        private string _controllerName;

        /// <summary>
        /// 当前Controller
        /// </summary>
        private ControllerBase _controller;
        
        /// <summary>
        /// 当前Context
        /// </summary>
        private AuthorizationContext _filterContext;

        /// <summary>
        /// 该Action对应的权限项名称
        /// </summary>
        public string RightName { get; set; }

        /// <summary>
        /// 该Action对应的操作权限
        /// </summary>
        public OperationRights Operation { get; set; }

        /// <summary>
        /// .ctor
        /// </summary>
        static RightAuthorizeAttribute()
        {
        }

        /// <summary>
        /// .ctor
        /// </summary>
        public RightAuthorizeAttribute()
        {
            this.Operation = OperationRights.None;
            this.RightName = null;
        }

        /// <summary>
        /// .ctor
        /// </summary>
        /// <param name="rightName">该Action对应的权限项名称</param>
        /// <param name="operation">该Action对应的操作权限</param>
        public RightAuthorizeAttribute(string rightName, OperationRights operation)
        {
            this.Operation = operation;
            this.RightName = rightName;
        }

        /// <summary>
        /// 提供一个入口点用于进行自定义授权检查
        /// </summary>
        /// <param name="filterContext">HTTP 上下文,它封装有关单个 HTTP 请求的所有 HTTP 特定的信息。</param>
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            _filterContext = filterContext;
            _controller = filterContext.Controller;
            _actionName = filterContext.ActionDescriptor.ActionName;
            _controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            if (string.IsNullOrEmpty(_controllerName))
            {
                _controllerName = filterContext.RouteData.Values["controller"].ToString().ToLower();
            }

            if (string.IsNullOrEmpty(_actionName))
            {
                _actionName = filterContext.RouteData.Values["action"].ToString().ToLower();
            }

            base.OnAuthorization(filterContext);
        }

        /// <summary>
        /// 验证过程
        /// </summary>
        /// <param name="httpContext">当前HTTP 上下文</param>
        /// <returns></returns>
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var controller = _controller as BaseController;

            // 验证权限信息
            return controller == null
                || controller.RightAuthorizeExcludeControllers.Any(p => string.Equals(p, this._controllerName, StringComparison.OrdinalIgnoreCase))
                || this.VerifyAuthorization(httpContext);
        }

        /// <summary>
        /// 验证不通过时调用
        /// </summary>
        /// <param name="filterContext">HTTP 上下文</param>
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            var controller = _controller as BaseController;
            if (controller != null)
            {
                var returnType = this.GetExpectedReturnType(filterContext);
                if (returnType == typeof(WhtrJsonResult))
                {
                    filterContext.Result = controller.GetCommonResult(
                        ResultState.UnAuthorize,
                        new Response()
                        {
                            Success = false,
                            Message = "没有权限"
                        });

                    return;
                }
            }

            base.HandleUnauthorizedRequest(filterContext);
        }

        /// <summary>
        /// 实际验证过程
        /// </summary>
        /// <param name="filterContext">当前上下文</param>
        /// <returns></returns>
        private bool VerifyAuthorization(HttpContextBase filterContext)
        {
            var controller = _controller as BaseController;
            if (controller == null)
            {
                return true;
            }

            var paramObj = GetFirstParamObject();
            if (paramObj !=null && paramObj.PlatformId != null)
            {
                
            }

            if (Operation == OperationRights.None || string.IsNullOrEmpty(this.RightName))
            {
                var key = (this._controllerName + "/" + this._actionName).ToLowerInvariant();

                var rightItem = controller.ActionRights.GetObjectWithoutException(key);
                if (rightItem == null)
                {
                    key = (this._controllerName + "/*").ToLowerInvariant();
                    rightItem = controller.ActionRights.GetObjectWithoutException(key);
                }

                if (rightItem != null)
                {
                    this.RightName = rightItem.RightName;
                    this.Operation = (OperationRights)Convert.ToInt32(rightItem.RightValue);
                }
            }

            if (Operation == OperationRights.None || string.IsNullOrEmpty(this.RightName))
            {
                return true;
            }

            return controller.Rights.HasRight(RightName, Operation);
        }

        /// <summary>
        /// 获取返回类型
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        /// <returns></returns>
        private Type GetExpectedReturnType(AuthorizationContext filterContext)
        {
            return (((ReflectedActionDescriptor)(filterContext.ActionDescriptor)).MethodInfo).ReturnType;
        }

        private Type GetFirstParamType(AuthorizationContext filterContext)
        {
            return filterContext.ActionDescriptor.GetParameters().Select(item => item.ParameterType).FirstOrDefault();
        }
        private dynamic GetFirstParamObject()
        {
            var paramNames = this._filterContext.ActionDescriptor.GetParameters();
            if (paramNames.Length > 0)
            {
                var parameterInfo = this._filterContext.Controller.ValueProvider.GetValue(paramNames[0].ParameterName);

                return parameterInfo;
            }

            return null;
        }
    }

 

自定义权限验证特性