- public class Auth : ActionFilterAttribute
- {
- private const string Origin = "Origin";
- private const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";
- private const string originHeaderdefault = "*";
- /// <summary>
- /// 走完api之后
- /// </summary>
- /// <param name="actionExecutedContext"></param>
- public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
- {
- actionExecutedContext.Response.Headers.Add(AccessControlAllowOrigin, originHeaderdefault);
- }
- /// <summary>
- /// 进api之前
- /// </summary>
- /// <param name="actionContext"></param>
- public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
- {
- base.OnActionExecuting(actionContext);
- //先判断时间戳
- long time = long.Parse(actionContext.ActionArguments["timestamp"].ToString());
- bool result = Tools.TimeHelp.IsTime(time, Convert.ToDouble(ConfigurationManager.AppSettings["TimestampInterval"]));
- if (!result)
- {
- //时间戳不正确
- Models.ClientModel model = new Models.ClientModel
- {
- result = false,
- message = "Time is not right!",
- code = 200,
- data = null
- };
- actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.OK, model);
- return;
- }
- Dictionary<string, object> dic = new Dictionary<string, object>();
- foreach (var item in actionContext.ActionArguments)
- {
- dic.Add(item.Key, item.Value);
- }
- //移除post的key
- if (dic.ContainsKey("postData"))
- {
- dic.Remove("postData");
- }
- if (dic.ContainsKey("signature"))
- {
- dic.Remove("signature");
- }
- //肯定能取到client
- string client = dic["client"].ToString();
- //得到secretkey
- string secretkey = string.Empty;
- if (!Models.Config.DIC_SUPPLIER.ContainsKey(client))
- {
- //没有找到客户
- Models.ClientModel model = new Models.ClientModel
- {
- result = false,
- message = "Can't find Client!",
- code = 200,
- data = null
- };
- actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.OK, model);
- return;
- }
- else {
- secretkey = Models.Config.DIC_SUPPLIER[client];
- }
- //sign签名
- string sign = Tools.SignHelper.Sign(secretkey, dic);
- string signature = actionContext.ActionArguments["signature"].ToString();
- if (!sign.Equals(signature))
- {
- //签名不正确
- Models.ClientModel model = new Models.ClientModel
- {
- result = false,
- message = "The signature is not correct!",
- code = 200,
- data = null
- };
- actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.OK, model);
- return;
- }
- }
- }
复制代码 生产环境的代码。
|