netcore ActionFilter 过滤器全局验证签名和接口

tech2024-07-07  60

netcore ActionFilter 过滤器全局验证签名和接口

一、新建一个类

/// <summary> /// 在Action运行的前、后运行(验证签名)Attribute /// </summary> public class VerifySignFilter : IActionFilter { private readonly IMemoryCache _imemorycache; public VerifySignFilter(IMemoryCache imemorycache) { _imemorycache = imemorycache; } /// <summary> /// 方法执行完------>再执行该方法 /// </summary> /// <param name="context"></param> public void OnActionExecuted(ActionExecutedContext context) { } /// <summary> /// 进入方法之前------>先执行该方法 /// </summary> /// <param name="context"></param> public void OnActionExecuting(ActionExecutingContext context) { //1.验证签名 if (!Utils.CheckSign(context.HttpContext)) { BuildErrorJson(context); return; } //2.验证接口超时 //string signature = HttpContext.Request.Headers["signature"]; var request = context.HttpContext.Request; string nonce = request.Headers["nonce"]; string appid = request.Headers["appid"]; string timespan = request.Headers["timespan"]; long timeout = Utils.DateTimeToUnix(Utils.GetUnixDateTime(timespan).AddMinutes(2)); if (string.IsNullOrEmpty(nonce) || string.IsNullOrEmpty(appid) || string.IsNullOrEmpty(timespan)) { BuildErrorJson(context, "nonce,timespan,appid不能为空!"); return; } string key = $"{appid}|{nonce}|{timeout}";//接口请求2分钟后过期 long now = Utils.DateTimeToUnix(DateTime.Now);//当前时间 if (Utils.Exists(_imemorycache, key)) { long time = _imemorycache.Get<long>(key);//过期时间 if (time < now) { Utils.Remove(_imemorycache, key); BuildErrorJson(context, "接口请求过期,请刷新重试!"); return; } } else { if (timeout < now) { BuildErrorJson(context, "时间戳无效!");//时间戳不能小于当前时间 return; } _imemorycache.Set<long>(key, timeout); } } private void BuildErrorJson(ActionExecutingContext context, string msg = "签名验证失败!") { context.HttpContext.Response.StatusCode = 200; context.HttpContext.Response.ContentType = "application/json"; context.Result = new JsonResult(new { msg = msg, code = 100 }); } }

二、ConfigureServices 过滤器全局注册

//过滤器注册 services.AddMvc( options => { options.Filters.Add<VerifySignFilter>(); } );

三、调用

最新回复(0)