自定义权限验证特性

/// <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;
        }
    }

 

转载于:https://www.cnblogs.com/zhshlimi/p/7268604.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值