webAPI過濾器添加參數簽名
阿新 • • 發佈:2018-01-30
iges tolower sign web pac 部分 ren etc getc
項目需求:
接口對安卓和IOS開發接口,需要房子用戶竄改數據請求接口。添加sign簽名校驗參數。
代碼如下:加上特性標簽就可以控制部分接口驗證
public class SignAuthorizeFilterAttribute : ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext filterContext) { var actionList = filterContext.ActionDescriptor.GetCustomAttributes<EncryptDataAttribute>();var controllList = filterContext.ControllerContext.ControllerDescriptor.GetCustomAttributes<EncryptDataAttribute>(); if (actionList.Any()|| controllList.Any()) { string key = ConfigSection.Get("Key"); if (!string.IsNullOrWhiteSpace(key)) {var result = new AjaxResCode(); //1.驗證入參 string token = HttpContext.Current.Request.Params["token"]; string appkey = HttpContext.Current.Request.Params["appkey"]; string timestamp = HttpContext.Current.Request.Params["timestamp"]; string digest = HttpContext.Current.Request.Params["digest"]; string v = HttpContext.Current.Request.Params["v"]; if (string.IsNullOrWhiteSpace(token) || string.IsNullOrWhiteSpace(appkey) || string.IsNullOrWhiteSpace(timestamp) || string.IsNullOrWhiteSpace(digest) || string.IsNullOrWhiteSpace(v)) { result.Message = "請求非法。。。。!"; result.ResultCode = (int)ResultCode.Nopermit; filterContext.Response = filterContext.Request.CreateResponse(HttpStatusCode.OK, result); } NameValueCollection coll = HttpContext.Current.Request.Form; StringBuilder paramStr = new StringBuilder(); var keys = new List<string>(); foreach (string param in coll.Keys) { if (!string.IsNullOrEmpty(param)) { keys.Add(param.ToLower()); } } keys.Sort(); foreach (string p in keys) { if (p != "digest") { if (!string.IsNullOrEmpty(coll[p])) { paramStr.Append(coll[p]); } } } paramStr.Append(key); if (DESEncrypt.MD5ToUpper(paramStr.ToString()) != digest) { result.Message = "請求非法!。。。。。"; result.ResultCode = (int)ResultCode.Nopermit; filterContext.Response = filterContext.Request.CreateResponse(HttpStatusCode.OK, result); } } } base.OnActionExecuting(filterContext); } }
webAPI過濾器添加參數簽名