예제 #1
0
        public void OnAuthorization(AuthorizationFilterContext filterContext)
        {
            filterContextInfo = new FilterContextInfo(filterContext);

            if (filterContextInfo.ControllerName == "Base")
            {
                throw new Exception("禁止访问基类控制器");
            }

            //不用检查
            if (Anonymous)
            {
                return;
            }

            #region  检查认证
            try
            {
                string token = filterContext.HttpContext.Request.Headers["cat-token"];
                try
                {
                    if (string.IsNullOrEmpty(token))
                    {
                        throw new Exception("用户身份认证未通过[token不能为空],请求数据失败");
                    }

                    token = AesHelper.AesDecrypt(token);
                    var auth = Serializer.JsonDeserialize <Cat.M.Book.Models.ModelBinder.ReturnModels.BookAuth>(token);
                    if (string.IsNullOrEmpty(auth.Openid))
                    {
                        throw new Exception("用户身份认证未通过[找不到指定的openid],请求数据失败");
                    }
                }
                catch (Exception ex)
                {
                    if (string.IsNullOrEmpty(ex.Message))
                    {
                        throw new Exception("用户身份认证未通过,请求数据失败");
                    }
                    else
                    {
                        throw ex;
                    }
                }
            }
            catch (Exception ex)
            {
                Microsoft.AspNetCore.Mvc.ContentResult contentResult = new Microsoft.AspNetCore.Mvc.ContentResult();
                contentResult.Content = ActionRes.Fail(ex.Message).ToJson();
                filterContext.Result  = contentResult;
                return;
            }
            #endregion
        }
        // OnActionExecuted 在执行操作方法后由 ASP.NET MVC 框架调用。
        // OnActionExecuting 在执行操作方法之前由 ASP.NET MVC 框架调用。
        // OnResultExecuted 在执行操作结果后由 ASP.NET MVC 框架调用。
        // OnResultExecuting 在执行操作结果之前由 ASP.NET MVC 框架调用。

        /// <summary>
        /// 在执行操作方法之前由 ASP.NET MVC 框架调用。
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            //检查是否免检页面
            bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true) ||
                                     filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true);

            if (skipAuthorization)
            {
                return;
            }

            #region 是否已经登陆
            var user = filterContext.HttpContext.User;
            userName = filterContext.HttpContext.User.Identity.Name;//取得当前用户名

            if (filterContext.HttpContext.Session["Employee"] == null || user == null || !user.Identity.IsAuthenticated)

            {
                filterContext.HttpContext.Session.RemoveAll();

                isState = false;
                filterContext.Result = new ContentResult {
                    Content = @"抱歉,您还未登录!"
                };
                filterContext.Result = new HttpUnauthorizedResult();
                return;
            }
            else
            {
                isState = true;
            }
            #endregion



            #region
            #endregion
            #region 权限验证


            GetEmployee(filterContext);//得到当前员工信息


            fcinfo = new FilterContextInfo(filterContext);
            string actionName    = fcinfo.ActionName;     //获取域名
            string contollerName = fcinfo.ControllerName; //获取 controllerName 名称

            ///检查操作权限
            CheckAuth(Employees, actionName, contollerName);

            if (isState)//如果满足
            {
                return;
                // filterContext.Result = new HttpUnauthorizedResult();//直接URL输入的页面地址跳转到登陆页
                // filterContext.Result = new RedirectResult("http://www.baidu.com");//也可以跳到别的站点
            }
            else
            {
                filterContext.Result = new ContentResult {
                    Content = @"抱歉,你不具有当前操作的权限!"
                };                                                                        // 直接返回 return Content("抱歉,你不具有当前操作的权限!")
            }

            #endregion
        }
        public void OnAuthorization(AuthorizationFilterContext filterContext)
        {
            filterContextInfo = new FilterContextInfo(filterContext);

            if (filterContextInfo.ControllerName == "Base")
            {
                throw new Exception("禁止访问基类控制器");
            }

            ////不用检查
            //if (Anonymous)
            //{
            //    return;
            //}

            //当类和方法都被标记【ApiAuthorizeFilterAttribute】,只取最后一个筛选器配置。即如果类和方法都被标记,则取的是方法上的筛选器
            var thisClassObj = filterContext.Filters.Where(w => w.ToString().EndsWith("ApiAuthorizeFilterAttribute")).Last() as ApiAuthorizeFilterAttribute;

            AuthorityIdentity = thisClassObj.AuthorityIdentity;

            //标记为“匿名”的方法或类不用检查
            if (AuthorityIdentity == AuthorityIdentityEnum.Anonymous)
            {
                return;
            }


            ErrorCode errorCode = ErrorCode.Default;

            #region
            try
            {
                try
                {
                    //检查认证
                    //string authority = filterContext.HttpContext.Request.Headers["cat-book-antd-pro-authority"];
                    //string userid = filterContext.HttpContext.Request.Headers["cat-book-antd-pro-userid"];
                    string token = ApiHelper.AuthToken;
                    if (string.IsNullOrEmpty(token))
                    {
                        errorCode = ErrorCode.user_no_authority;
                        throw new Exception("用户身份认证未通过[token不能为空],请求数据失败");
                    }

                    token = AesHelper.AesDecrypt(token);
                    var auth = Serializer.JsonDeserialize <Cat.M.Book.Models.ModelBinder.ReturnModels.ApiAuth>(token);
                    if (string.IsNullOrEmpty(auth.User_Id))
                    {
                        errorCode = ErrorCode.user_no_authority;
                        throw new Exception("");
                    }
                    //if (auth.User_Id != userid) throw new Exception();

                    //检查用户状态
                    var user = Cat.M.Public.Services.AllServices.SysAccountService.GetSingle(w => w.User_Id == auth.User_Id);
                    if (user == null)
                    {
                        errorCode = ErrorCode.user_not_found;
                        throw new Exception("没有找到用户,可能已被删除");
                    }
                    if (user.Disable == true)
                    {
                        errorCode = ErrorCode.user_disabled;
                        throw new Exception("当前登录用户已被禁用,请找超级管理员解除");
                    }
                    if ((user.Password.Substring(0, 5) + user.Password.Substring(user.Password.Length - 5, 5)) != auth.Pwd_Incomplete)
                    {
                        errorCode = ErrorCode.user_pwd_modified;
                        throw new Exception("当前登录用户密码已修改,请重新登录");
                    }
                    if ((DateTime.Now - auth.LoginTime).TotalDays > Cat.Foundation.ConfigManager.CatSettings.LogonCredentialSaveDay)
                    {
                        errorCode = ErrorCode.user_logon_overdue;
                        throw new Exception("登录凭证已过期,您需要重新登录");
                    }

                    //检查授权
                    if (!user.Authority.Split(",", StringSplitOptions.RemoveEmptyEntries).Contains(AuthorityIdentityEnum.Administrator.ToString().ToLower()))
                    {
                        //当前登录用户没有管理员权限
                        if (AuthorityIdentity == AuthorityIdentityEnum.Administrator)
                        {
                            //当前访问的类或方法被标记为管理员
                            throw new Exception("当前登录用户没有权限进行此操作");
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (string.IsNullOrEmpty(ex.Message))
                    {
                        throw new Exception("用户身份认证未通过,请求数据失败");
                    }
                    else
                    {
                        throw ex;
                    }
                }
            }
            catch (Exception ex)
            {
                Microsoft.AspNetCore.Mvc.ContentResult contentResult = new Microsoft.AspNetCore.Mvc.ContentResult();
                contentResult.Content = ActionRes.Fail((int)errorCode, ex.Message).ToJson();
                filterContext.Result  = contentResult;
                return;
            }
            #endregion
        }