Example #1
0
        /// <summary>
        /// 根据用户名获取token
        /// </summary>
        /// <param name="appkey"></param>
        /// <returns></returns>

        public HttpResponseMessage GetToken(string appkey, string appsecret)
        {
            ResultMsg resultMsg = null;

            //判断参数是否合法
            if (string.IsNullOrEmpty(appkey))
            {
                resultMsg            = new ResultMsg();
                resultMsg.StatusCode = (int)StatusCodeEnum.ParameterError;
                resultMsg.Message    = StatusCodeEnum.ParameterError.GetEnumText();
                resultMsg.Data       = "";
                return(HttpResponseExtension.ToJson(resultMsg));
            }

            //插入缓存
            Token token = (Token)HttpRuntime.Cache.Get(appkey);

            if (token == null)
            {
                token            = new Token();
                token.AppKey     = appkey;
                token.SignToken  = Guid.NewGuid();
                token.ExpireTime = DateTime.Now.AddDays(1);

                HttpRuntime.Cache.Insert(token.AppKey.ToString(), token, null, token.ExpireTime, TimeSpan.Zero);
            }

            //返回token信息
            resultMsg            = new ResultMsg();
            resultMsg.StatusCode = (int)StatusCodeEnum.Success;
            resultMsg.Message    = StatusCodeEnum.Success.GetEnumText();
            resultMsg.Data       = token;

            return(HttpResponseExtension.ToJson(resultMsg));
        }
        public HttpResponseMessage AddProudct(Product product)
        {
            var resultMsg = new HttpResponseMsg
            {
                StatusCode = (int)StatusCodeEnum.Success,
                Info       = StatusCodeEnum.Success.GetEnumText(),
                Data       = product
            };

            return(HttpResponseExtension.ToJson(JsonConvert.SerializeObject(resultMsg)));
        }
        public HttpResponseMessage GetProduct(string id)
        {
            var product = new Product {
                Id = 1, Name = "哇哈哈", Count = 10, Price = 38.8
            };
            var resultMsg = new HttpResponseMsg
            {
                StatusCode = (int)StatusCodeEnum.Success,
                Info       = StatusCodeEnum.Success.GetEnumText(),
                Data       = product
            };

            return(HttpResponseExtension.ToJson(JsonConvert.SerializeObject(resultMsg)));
        }
Example #4
0
        /// <summary>
        /// 根据用户名获取token
        /// </summary>
        /// <param name="staffId"></param>
        /// <returns></returns>
        public HttpResponseMessage GetToken(string staffId)
        {
            HttpResponseMsg resultMsg;
            int             id;

            //判断参数是否合法
            if (string.IsNullOrEmpty(staffId) || (!int.TryParse(staffId, out id)))
            {
                resultMsg = new HttpResponseMsg
                {
                    StatusCode = (int)StatusCodeEnum.ParameterError,
                    Info       = StatusCodeEnum.ParameterError.GetEnumText(),
                    Data       = ""
                };
                return(HttpResponseExtension.ToJson(JsonConvert.SerializeObject(resultMsg)));
            }

            //插入缓存
            TokenInfo token = (TokenInfo)HttpRuntime.Cache.Get(id.ToString());

            if (HttpRuntime.Cache.Get(id.ToString()) == null)
            {
                token = new TokenInfo
                {
                    StaffId    = id,
                    SignToken  = Guid.NewGuid(),
                    ExpireTime = DateTime.Now.AddDays(1)
                };
                HttpRuntime.Cache.Insert(token.StaffId.ToString(), token, null, token.ExpireTime, TimeSpan.Zero);
            }

            //返回token信息
            resultMsg = new HttpResponseMsg
            {
                StatusCode = (int)StatusCodeEnum.Success,
                Info       = "",
                Data       = token
            };

            return(HttpResponseExtension.ToJson(JsonConvert.SerializeObject(resultMsg)));
        }
        public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext filterContext)
        {
            ResultMsg result = null;
            string    signKey = string.Empty, timespan = string.Empty, nonce = string.Empty, signature = string.Empty;
            //判断请求的消息中是否包括判断参数
            var request = filterContext.Request;

            if (request.Headers.Contains("signKey"))
            {
                signKey = request.Headers.GetValues("signKey").FirstOrDefault();
            }
            if (request.Headers.Contains("timespan"))
            {
                timespan = request.Headers.GetValues("timespan").FirstOrDefault();
            }
            if (request.Headers.Contains("nonce"))
            {
                nonce = request.Headers.GetValues("nonce").FirstOrDefault();
            }
            if (request.Headers.Contains("signature"))
            {
                signature = request.Headers.GetValues("signature").FirstOrDefault();
            }

            //如果方法是GetToken,则不需要验证
            if (filterContext.ActionDescriptor.ActionName.ToLower() == "gettoken")
            {
                if (string.IsNullOrEmpty(signKey) || string.IsNullOrEmpty(timespan) || string.IsNullOrEmpty(nonce))
                {
                    result = new ResultMsg((int)ExceptionStatus.ParameterError, EnumExtension.GetEnumText(ExceptionStatus.ParameterError), null);
                    filterContext.Response = HttpResponseExtension.ToJson(result);
                    base.OnActionExecuting(filterContext);
                    return;
                }
                else
                {
                    base.OnActionExecuting(filterContext);
                    return;
                }
            }
            DbLogger.LogWriteMessage("测试参数");
            string signtoken = string.Empty;

            //判断是否包含以下参数
            if (string.IsNullOrEmpty(signKey) || string.IsNullOrEmpty(timespan) || string.IsNullOrEmpty(nonce) || string.IsNullOrEmpty(signature))
            {
                result = new ResultMsg((int)ExceptionStatus.ParameterError, EnumExtension.GetEnumText(ExceptionStatus.ParameterError), null);
                filterContext.Response = HttpResponseExtension.ToJson(result);
                base.OnActionExecuting(filterContext);
                return;
            }

            DbLogger.LogWriteMessage("测试是否在有效时间内");
            //判断是否在有效时间内
            double ts1 = 0;
            double ts2 = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalMilliseconds;
            bool   timespanValidate = double.TryParse(timespan, out ts1);
            double ts   = ts2 - ts1;
            bool   falg = ts > int.Parse(WebConfig.UrlExpireTime) * 1000;

            if (!timespanValidate || falg)
            {
                result = new ResultMsg((int)ExceptionStatus.URLExpireError, EnumExtension.GetEnumText(ExceptionStatus.URLExpireError), null);
                filterContext.Response = HttpResponseExtension.ToJson(result);
                base.OnActionExecuting(filterContext);
                return;
            }

            DbLogger.LogWriteMessage("测试token是否有效");
            //判断token是否有效
            Token token = HttpRuntime.Cache.Get(string.Format("{0}{1}", WebConfig.signKey, signKey)) as Token;

            if (token == null)
            {
                result = new ResultMsg((int)ExceptionStatus.TokenInvalid, EnumExtension.GetEnumText(ExceptionStatus.TokenInvalid), null);
                filterContext.Response = HttpResponseExtension.ToJson(result);
                base.OnActionExecuting(filterContext);
                return;
            }
            else
            {
                signtoken = token.signToken;
            }

            DbLogger.LogWriteMessage("判断http调用方式");
            string data = string.Empty;
            //判断http调用方式
            string method = request.Method.Method.ToUpper();

            switch (method)
            {
            case "POST":
                Stream       stream       = HttpContext.Current.Request.InputStream;
                string       responseJson = string.Empty;
                StreamReader streamReader = new StreamReader(stream);
                data = streamReader.ReadToEnd();
                break;

            case "GET":
                NameValueCollection form = HttpContext.Current.Request.QueryString;
                //第一步:取出所有get参数
                IDictionary <string, string> parameters = new Dictionary <string, string>();
                for (int f = 0; f < form.Count; f++)
                {
                    string key = form.Keys[f];
                    parameters.Add(key, form[key]);
                }

                // 第二步:把字典按Key的字母顺序排序
                IDictionary <string, string> sortedParams        = new SortedDictionary <string, string>(parameters);
                IEnumerator <KeyValuePair <string, string> > dem = sortedParams.GetEnumerator();

                // 第三步:把所有参数名和参数值串在一起
                StringBuilder query = new StringBuilder();
                while (dem.MoveNext())
                {
                    string key   = dem.Current.Key;
                    string value = dem.Current.Value;
                    if (!string.IsNullOrEmpty(key))
                    {
                        query.Append(key).Append(value);
                    }
                }
                data = query.ToString();
                break;

            default:
                result = new ResultMsg((int)ExceptionStatus.HttpMehtodError, EnumExtension.GetEnumText(ExceptionStatus.HttpMehtodError), null);
                filterContext.Response = HttpResponseExtension.ToJson(result);
                base.OnActionExecuting(filterContext);
                break;
            }

            DbLogger.LogWriteMessage("验证签名信息是否符合");
            //验证签名信息是否符合
            bool valida = ValidateSign.Validate(signKey, timespan, nonce, signtoken, data, signature);

            if (!valida)
            {
                result = new ResultMsg((int)ExceptionStatus.HttpRequestError, EnumExtension.GetEnumText(ExceptionStatus.HttpRequestError), null);
                filterContext.Response = HttpResponseExtension.ToJson(result);
                base.OnActionExecuting(filterContext);
                return;
            }
            else
            {
                base.OnActionExecuting(filterContext);
            }
        }
Example #6
0
        public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            HttpResponseMsg resultMsg;
            var             request = actionContext.Request;
            string          method = request.Method.Method;
            string          staffid = String.Empty, timestamp = string.Empty, nonce = string.Empty, signature = string.Empty;
            int             id;

            if (request.Headers.Contains("staffid"))
            {
                staffid = HttpUtility.UrlDecode(request.Headers.GetValues("staffid").FirstOrDefault());
            }
            if (request.Headers.Contains("timestamp"))
            {
                timestamp = HttpUtility.UrlDecode(request.Headers.GetValues("timestamp").FirstOrDefault());
            }
            if (request.Headers.Contains("nonce"))
            {
                nonce = HttpUtility.UrlDecode(request.Headers.GetValues("nonce").FirstOrDefault());
            }

            if (request.Headers.Contains("signature"))
            {
                signature = HttpUtility.UrlDecode(request.Headers.GetValues("signature").FirstOrDefault());
            }

            //GetToken方法不需要进行签名验证
            if (actionContext.ActionDescriptor.ActionName == "GetToken")
            {
                if (string.IsNullOrEmpty(staffid) || (!int.TryParse(staffid, out id) || string.IsNullOrEmpty(timestamp) || string.IsNullOrEmpty(nonce)))
                {
                    resultMsg = new HttpResponseMsg
                    {
                        StatusCode = (int)StatusCodeEnum.ParameterError,
                        Info       = StatusCodeEnum.ParameterError.GetEnumText(),
                        Data       = ""
                    };
                    actionContext.Response = HttpResponseExtension.ToJson(JsonConvert.SerializeObject(resultMsg));
                    base.OnActionExecuting(actionContext);
                    return;
                }
                else
                {
                    base.OnActionExecuting(actionContext);
                    return;
                }
            }

            //判断请求头是否包含以下参数
            if (string.IsNullOrEmpty(staffid) || (!int.TryParse(staffid, out id) || string.IsNullOrEmpty(timestamp) || string.IsNullOrEmpty(nonce) || string.IsNullOrEmpty(signature)))
            {
                resultMsg              = new HttpResponseMsg();
                resultMsg.StatusCode   = (int)StatusCodeEnum.ParameterError;
                resultMsg.Info         = StatusCodeEnum.ParameterError.GetEnumText();
                resultMsg.Data         = "";
                actionContext.Response = HttpResponseExtension.ToJson(JsonConvert.SerializeObject(resultMsg));
                base.OnActionExecuting(actionContext);
                return;
            }

            //判断timespan是否有效
            double ts1;
            double ts2  = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalMilliseconds;
            bool   timespanvalidate = double.TryParse(timestamp, out ts1);
            double ts   = ts2 - ts1;
            bool   falg = ts > int.Parse(WebSettingsConfig.UrlExpireTime) * 1000;

            if (falg || (!timespanvalidate))
            {
                resultMsg = new HttpResponseMsg
                {
                    StatusCode = (int)StatusCodeEnum.URLExpireError,
                    Info       = StatusCodeEnum.URLExpireError.GetEnumText(),
                    Data       = ""
                };
                actionContext.Response = HttpResponseExtension.ToJson(JsonConvert.SerializeObject(resultMsg));
                base.OnActionExecuting(actionContext);
                return;
            }

            //判断token是否有效
            TokenInfo token = (TokenInfo)HttpRuntime.Cache.Get(id.ToString());

            if (HttpRuntime.Cache.Get(id.ToString()) == null)
            {
                resultMsg = new HttpResponseMsg
                {
                    StatusCode = (int)StatusCodeEnum.TokenInvalid,
                    Info       = StatusCodeEnum.TokenInvalid.GetEnumText(),
                    Data       = ""
                };
                actionContext.Response = HttpResponseExtension.ToJson(JsonConvert.SerializeObject(resultMsg));
                base.OnActionExecuting(actionContext);
                return;
            }

            var signtoken = token.SignToken.ToString();

            //根据请求类型拼接参数
            NameValueCollection form = HttpContext.Current.Request.QueryString;
            string data;

            switch (method)
            {
            case "POST":
                Stream       stream       = HttpContext.Current.Request.InputStream;
                string       responseJson = string.Empty;
                StreamReader streamReader = new StreamReader(stream);
                data = streamReader.ReadToEnd();
                break;

            case "GET":
                //第一步:取出所有get参数
                IDictionary <string, string> parameters = new Dictionary <string, string>();
                for (int f = 0; f < form.Count; f++)
                {
                    string key = form.Keys[f];
                    parameters.Add(key, form[key]);
                }

                // 第二步:把字典按Key的字母顺序排序
                IDictionary <string, string> sortedParams        = new SortedDictionary <string, string>(parameters);
                IEnumerator <KeyValuePair <string, string> > dem = sortedParams.GetEnumerator();

                // 第三步:把所有参数名和参数值串在一起
                StringBuilder query = new StringBuilder();
                while (dem.MoveNext())
                {
                    string key   = dem.Current.Key;
                    string value = dem.Current.Value;
                    if (!string.IsNullOrEmpty(key))
                    {
                        query.Append(key).Append(value);
                    }
                }
                data = query.ToString();
                break;

            default:
                resultMsg              = new HttpResponseMsg();
                resultMsg.StatusCode   = (int)StatusCodeEnum.HttpMehtodError;
                resultMsg.Info         = StatusCodeEnum.HttpMehtodError.GetEnumText();
                resultMsg.Data         = "";
                actionContext.Response = HttpResponseExtension.ToJson(JsonConvert.SerializeObject(resultMsg));
                base.OnActionExecuting(actionContext);
                return;
            }

            bool result = SignExtension.Validate(timestamp, nonce, id, signtoken, data, signature);

            if (!result)
            {
                resultMsg              = new HttpResponseMsg();
                resultMsg.StatusCode   = (int)StatusCodeEnum.HttpRequestError;
                resultMsg.Info         = StatusCodeEnum.HttpRequestError.GetEnumText();
                resultMsg.Data         = "";
                actionContext.Response = HttpResponseExtension.ToJson(JsonConvert.SerializeObject(resultMsg));
                base.OnActionExecuting(actionContext);
            }
            else
            {
                base.OnActionExecuting(actionContext);
            }
        }