/// <summary> /// Action执行之前执行 /// </summary> /// <param name="context">过滤器上下文</param> public void OnActionExecuting(ActionExecutingContext context) { if (context.ContainsFilter <NoJsonParamterAttribute>()) { return; } //参数映射:支持application/json string contentType = context.HttpContext.Request.ContentType; if (!contentType.IsNullOrEmpty() && contentType.Contains("application/json")) { var actionParameters = context.ActionDescriptor.Parameters; var allParamters = HttpHelper.GetAllRequestParams(context.HttpContext); var actionArguments = context.ActionArguments; actionParameters.ForEach(aParamter => { string key = aParamter.Name; if (allParamters.ContainsKey(key)) { actionArguments[key] = allParamters[key]?.ToString()?.ChangeType_ByConvert(aParamter.ParameterType); } else { try { actionArguments[key] = allParamters.ToJson().ToObject(aParamter.ParameterType); } catch { } } }); } }
/// <summary> /// Action执行之前执行 /// </summary> /// <param name="context">过滤器上下文</param> public void OnActionExecuting(ActionExecutingContext context) { try { if (context.ContainsFilter <NoCheckJWTAttribute>() || GlobalSwitch.RunMode == RunMode.LocalTest) { return; } var req = context.HttpContext.Request; string token = req.GetToken(); if (!JWTHelper.CheckToken(token, JWTHelper.JWTSecret)) { context.Result = Error("token校验失败!", _errorCode); return; } var payload = JWTHelper.GetPayload <JWTPayload>(token); if (payload.Expire < DateTime.Now) { context.Result = Error("token过期!", _errorCode); return; } } catch (Exception ex) { context.Result = Error(ex.Message, _errorCode); } }
/// <summary> /// Action执行之前执行 /// </summary> /// <param name="filterContext">过滤器上下文</param> public void OnActionExecuting(ActionExecutingContext filterContext) { IPermissionManage PermissionManage = AutofacHelper.GetService <IPermissionManage>(); IUrlPermissionManage UrlPermissionManage = AutofacHelper.GetService <IUrlPermissionManage>(); //若为本地测试,则不需要校验 if (GlobalSwitch.RunModel == RunModel.LocalTest) { return; } AjaxResult res = new AjaxResult(); //判断是否需要校验 if (filterContext.ContainsFilter <IgnoreAppIdPermissionAttribute>()) { return; } var allRequestParams = HttpHelper.GetAllRequestParams(filterContext.HttpContext); if (!allRequestParams.ContainsKey("appId")) { res.Success = false; res.Msg = "缺少appId参数!"; filterContext.Result = new ContentResult { Content = res.ToJson() }; return; } string appId = allRequestParams["appId"]?.ToString(); var allUrlPermissions = UrlPermissionManage.GetAllUrlPermissions(); string requestUrl = filterContext.HttpContext.Request.Path; var thePermission = allUrlPermissions.Where(x => requestUrl.Contains(x.Url.ToLower())).FirstOrDefault(); if (thePermission == null) { return; } string needPermission = thePermission.PermissionValue; bool hasPermission = PermissionManage.GetAppIdPermissionValues(appId).Any(x => x.ToLower() == needPermission.ToLower()); if (hasPermission) { return; } else { res.Success = false; res.Msg = "权限不足!访问失败!"; filterContext.Result = new ContentResult { Content = res.ToJson() }; } }
/// <summary> /// Action执行之前执行 /// </summary> /// <param name="context">过滤器上下文</param> public async override Task OnActionExecuting(ActionExecutingContext context) { if (context.ContainsFilter <NoApiPermissionAttribute>()) { return; } IPermissionBusiness permissionBus = AutofacHelper.GetScopeService <IPermissionBusiness>(); var permissions = await permissionBus.GetUserPermissionValuesAsync(Operator.UserId); if (!permissions.Contains(_permissionValue)) { context.Result = Error("权限不足!"); } }
/// <summary> /// Action执行之前执行 /// </summary> /// <param name="context">过滤器上下文</param> public async override Task OnActionExecuting(ActionExecutingContext context) { if (context.ContainsFilter <NoApiPermissionAttribute>()) { return; } IServiceProvider serviceProvider = context.HttpContext.RequestServices; IPermissionBusiness _permissionBus = serviceProvider.GetService <IPermissionBusiness>(); IOperator _operator = serviceProvider.GetService <IOperator>(); var permissions = await _permissionBus.GetUserPermissionValuesAsync(_operator.UserId); if (!permissions.Contains(_permissionValue)) { context.Result = Error("权限不足!"); } }
/// <summary> /// Action执行之前执行 /// </summary> /// <param name="filterContext">过滤器上下文</param> public void OnActionExecuting(ActionExecutingContext filterContext) { IPermissionManage PermissionManage = AutofacHelper.GetScopeService <IPermissionManage>(); IUrlPermissionManage UrlPermissionManage = AutofacHelper.GetScopeService <IUrlPermissionManage>(); //若为本地测试,则不需要校验 if (GlobalSwitch.RunModel == RunModel.LocalTest) { return; } //判断是否需要校验 if (filterContext.ContainsFilter <IgnoreUrlPermissionAttribute>()) { return; } var allUrlPermissions = UrlPermissionManage.GetAllUrlPermissions(); string requestUrl = filterContext.HttpContext.Request.Path; var thePermission = allUrlPermissions.Where(x => requestUrl.ToLower().Contains(x.Url.ToLower())).FirstOrDefault(); if (thePermission == null) { return; } string needPermission = thePermission.PermissionValue; bool hasPermission = PermissionManage.GetOperatorPermissionValues().Any(x => x.ToLower() == needPermission.ToLower()); if (hasPermission) { return; } else { AjaxResult res = new AjaxResult { Success = false, Msg = "权限不足!无法访问!" }; filterContext.Result = new ContentResult { Content = res.ToJson(), ContentType = "application/json;charset=utf-8" }; } }
public override async Task OnActionExecuting(ActionExecutingContext context) { if (context.ContainsFilter <NoCheckJWTAttribute>()) { return; } try { var req = context.HttpContext.Request; string token = req.GetToken(); if (token.IsNullOrEmpty()) { context.Result = Error("缺少token", _errorCode); return; } //if (!JWTHelper.CheckToken(token, JWTHelper.JWTSecret)) //{ // context.Result = Error("token校验失败!", _errorCode); // return; //} //var payload = JWTHelper.GetPayload<JWTPayload>(token); //if (payload.Expire < DateTime.Now) //{ // context.Result = Error("token过期!", _errorCode); // return; //} } catch (Exception ex) { context.Result = Error(ex.Message, _errorCode); } await Task.CompletedTask; }
/// <summary> /// Action执行之前执行 /// </summary> /// <param name="filterContext"></param> public async override Task OnActionExecuting(ActionExecutingContext filterContext) { //判断是否需要签名 if (filterContext.ContainsFilter <IgnoreSignAttribute>()) { return; } var request = filterContext.HttpContext.Request; IServiceProvider serviceProvider = filterContext.HttpContext.RequestServices; IBase_AppSecretBusiness appSecretBus = serviceProvider.GetService <IBase_AppSecretBusiness>(); ILogger logger = serviceProvider.GetService <ILogger <CheckSignAttribute> >(); var cache = serviceProvider.GetService <IDistributedCache>(); string appId = request.Headers["appId"].ToString(); if (appId.IsNullOrEmpty()) { ReturnError("缺少header:appId"); return; } string time = request.Headers["time"].ToString(); if (time.IsNullOrEmpty()) { ReturnError("缺少header:time"); return; } if (time.ToDateTime() < DateTime.Now.AddMinutes(-5) || time.ToDateTime() > DateTime.Now.AddMinutes(5)) { ReturnError("time过期"); return; } string guid = request.Headers["guid"].ToString(); if (guid.IsNullOrEmpty()) { ReturnError("缺少header:guid"); return; } string guidKey = $"ApiGuid_{guid}"; if (cache.GetString(guidKey).IsNullOrEmpty()) { cache.SetString(guidKey, "1", new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10) }); } else { ReturnError("禁止重复调用!"); return; } request.EnableBuffering(); string body = await request.Body.ReadToStringAsync(); string sign = request.Headers["sign"].ToString(); if (sign.IsNullOrEmpty()) { ReturnError("缺少header:sign"); return; } string appSecret = await appSecretBus.GetAppSecretAsync(appId); if (appSecret.IsNullOrEmpty()) { ReturnError("header:appId无效"); return; } string newSign = HttpHelper.BuildApiSign(appId, appSecret, guid, time.ToDateTime(), body); if (sign != newSign) { string log = $@"sign签名错误! headers:{request.Headers.ToJson()} body:{body} 正确sign:{newSign} "; logger.LogWarning(log); ReturnError("header:sign签名错误"); return; } void ReturnError(string msg) { filterContext.Result = Error(msg); } }
/// <summary> /// Action执行之前执行 /// </summary> /// <param name="filterContext">过滤器上下文</param> public void OnActionExecuting(ActionExecutingContext filterContext) { IOperator Operator = AutofacHelper.GetService <IOperator>(); IBusHelper BusHelper = AutofacHelper.GetService <IBusHelper>(); var request = filterContext.HttpContext.Request; try { //若为本地测试,则不需要登录 if (GlobalSwitch.RunModel == RunModel.LocalTest) { return; } //判断是否需要登录 if (filterContext.ContainsFilter <IgnoreLoginAttribute>()) { return; } //转到登录 if (!Operator.Logged()) { RedirectToLogin(); } } catch (Exception ex) { BusHelper.HandleException(ex); RedirectToLogin(); } void RedirectToLogin() { if (request.IsAjaxRequest()) { filterContext.Result = new ContentResult { Content = new AjaxResult { Success = false, ErrorCode = 1, Msg = "未登录" }.ToJson(), ContentType = "application/json;charset=UTF-8" }; } else { UrlHelper urlHelper = new UrlHelper(filterContext); string loginUrl = urlHelper.Content("~/Home/Login"); string script = $@" <html> <script> top.location.href = '{loginUrl}'; </script> </html> "; filterContext.Result = new ContentResult { Content = script, ContentType = "text/html" }; } } }
/// <summary> /// Action执行之前执行 /// </summary> /// <param name="filterContext"></param> public void OnActionExecuting(ActionExecutingContext filterContext) { IBase_AppSecretBusiness appSecretBus = AutofacHelper.GetService <IBase_AppSecretBusiness>(); //若为本地测试,则不需要校验 if (GlobalSwitch.RunModel == RunModel.LocalTest) { return; } //判断是否需要签名 if (filterContext.ContainsFilter <IgnoreSignAttribute>()) { return; } var request = filterContext.HttpContext.Request; string appId = request.Headers["appId"].ToString(); if (appId.IsNullOrEmpty()) { ReturnError("缺少header:appId"); return; } string time = request.Headers["time"].ToString(); if (time.IsNullOrEmpty()) { ReturnError("缺少header:time"); return; } if (time.ToDateTime() < DateTime.Now.AddMinutes(-5) || time.ToDateTime() > DateTime.Now.AddMinutes(5)) { ReturnError("time过期"); return; } string guid = request.Headers["guid"].ToString(); if (guid.IsNullOrEmpty()) { ReturnError("缺少header:guid"); return; } string guidKey = $"{GlobalSwitch.ProjectName}_apiGuid_{guid}"; if (CacheHelper.Cache.GetCache(guidKey).IsNullOrEmpty()) { CacheHelper.Cache.SetCache(guidKey, "1", new TimeSpan(0, 10, 0)); } else { ReturnError("禁止重复调用!"); return; } string body = request.Body.ReadToString(); string sign = request.Headers["sign"].ToString(); if (sign.IsNullOrEmpty()) { ReturnError("缺少header:sign"); return; } string appSecret = appSecretBus.GetAppSecret(appId); if (appSecret.IsNullOrEmpty()) { ReturnError("header:appId无效"); return; } string newSign = HttpHelper.BuildApiSign(appId, appSecret, guid, time.ToDateTime(), body); if (sign != newSign) { ReturnError("header:sign签名错误"); return; } void ReturnError(string msg) { AjaxResult res = new AjaxResult { Success = false, Msg = msg }; filterContext.Result = new ContentResult { Content = res.ToJson(), ContentType = "application/json;charset=utf-8" }; } }
/// <summary> /// Action执行之前执行 /// </summary> /// <param name="filterContext"></param> public async override Task OnActionExecuting(ActionExecutingContext filterContext) { IBase_AppSecretBusiness appSecretBus = AutofacHelper.GetScopeService <IBase_AppSecretBusiness>(); ILogger logger = AutofacHelper.GetScopeService <ILogger>(); //若为本地测试,则不需要校验 if (GlobalSwitch.RunMode == RunMode.LocalTest) { return; } //判断是否需要签名 if (filterContext.ContainsFilter <IgnoreSignAttribute>()) { return; } var request = filterContext.HttpContext.Request; string appId = request.Headers["appId"].ToString(); if (appId.IsNullOrEmpty()) { ReturnError("缺少header:appId"); return; } string time = request.Headers["time"].ToString(); if (time.IsNullOrEmpty()) { ReturnError("缺少header:time"); return; } if (time.ToDateTime() < DateTime.Now.AddMinutes(-5) || time.ToDateTime() > DateTime.Now.AddMinutes(5)) { ReturnError("time过期"); return; } string guid = request.Headers["guid"].ToString(); if (guid.IsNullOrEmpty()) { ReturnError("缺少header:guid"); return; } string guidKey = $"{GlobalSwitch.ProjectName}_apiGuid_{guid}"; if (CacheHelper.Cache.GetCache(guidKey).IsNullOrEmpty()) { CacheHelper.Cache.SetCache(guidKey, "1", new TimeSpan(0, 10, 0)); } else { ReturnError("禁止重复调用!"); return; } string body = request.Body.ReadToString(); string sign = request.Headers["sign"].ToString(); if (sign.IsNullOrEmpty()) { ReturnError("缺少header:sign"); return; } string appSecret = await appSecretBus.GetAppSecretAsync(appId); if (appSecret.IsNullOrEmpty()) { ReturnError("header:appId无效"); return; } string newSign = HttpHelper.BuildApiSign(appId, appSecret, guid, time.ToDateTime(), body); if (sign != newSign) { string log = $@"header:sign签名错误! headers:{request.Headers.ToJson()} body:{body} 正确sign:{newSign} "; logger.Error(LogType.系统异常, log); ReturnError("header:sign签名错误"); return; } void ReturnError(string msg) { filterContext.Result = Error(msg); } }