Example #1
0
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            if (!_verifySignOption.Enable || _verifySignOption.Scheme?.ToLower() != "attribute")
            {
                goto gotoNext;
            }
            var descriptor          = (Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)context.ActionDescriptor;
            var attributeController = (IgnoreSignAttribute)descriptor.ControllerTypeInfo.GetCustomAttributes(typeof(IgnoreSignAttribute), true).FirstOrDefault();

            if (attributeController != null)
            {
                goto gotoNext;
            }

            var attribute = (IgnoreSignAttribute)descriptor.MethodInfo.GetCustomAttributes(typeof(IgnoreSignAttribute), true).FirstOrDefault();

            if (attribute != null)
            {
                goto gotoNext;
            }

            if (!GetSignValue(context.HttpContext.Request))
            {
                SignCommon.BuildErrorJson(context);
                await Task.CompletedTask;
                return;
            }
            else
            {
                goto gotoNext;
            }

gotoNext:
            await next();
        }
Example #2
0
        /// <summary>
        /// 签名算法;支持hmac-sha256;md5
        /// </summary>
        /// <param name="message"></param>
        /// <param name="secret"></param>
        /// <param name="signMethod">哈希算法,默认HMACSHA256</param>
        /// <returns>签名16进制</returns>
        public virtual string GetSignhHash(string message, string secret, EncryptEnum signMethod = EncryptEnum.Default)
        {
            if (signMethod.HasFlag(EncryptEnum.Default) || signMethod.HasFlag(EncryptEnum.SignHMACSHA256))
            {
                return(SignCommon.GetHMACSHA256Sign(message, secret));
            }

            else if (signMethod.HasFlag(EncryptEnum.SignSHA256))
            {
                return(SignCommon.GetSHA256Sign(message, secret));
            }
            else if (signMethod.HasFlag(EncryptEnum.SignMD5))
            {
                return(SignCommon.CreateMD5(message, secret));
            }
            else
            {
                return(SignCommon.GetHMACSHA256Sign(message, secret));
            }
        }
 /// <summary>
 ///
 /// </summary>
 /// <param name="message"></param>
 /// <param name="secret"></param>
 /// <returns>签名16进制</returns>
 public virtual string GetSignhHash(string message, string secret)
 {
     return(SignCommon.GetSignhHash(message, secret));
 }
Example #4
0
        private async Task <Tuple <bool, string> > GetSignValue(HttpContext request, RequestCacheData requestCacheData, VerifySignOption verifySignOption, IOperationFilter _verifySignCommon)
        {
            try
            {
                var convertedDictionatry = request.Request.Query.ToDictionary(s => s.Key, s => s.Value);
                var queryDic             = new Dictionary <string, string>();
                foreach (var item in convertedDictionatry)
                {
                    queryDic.Add(item.Key.ToLower(), item.Value);
                }

                var encryptEnum = EncryptEnum.Default;

                var commonParameters = verifySignOption.CommonParameters;

                if (!queryDic.ContainsKey(commonParameters.TimestampName) || !queryDic.ContainsKey(commonParameters.AppIdName) || !queryDic.ContainsKey(commonParameters.SignName))
                {
                    _logger.LogWarning("方式:[Middleware] url参数中未找到签名所需参数[timestamp];[appid];[EncryptFlag]或[sign]");
                    return(Tuple.Create <bool, string>(false, "签名参数缺失"));
                }

                if (queryDic.ContainsKey(commonParameters.EncryptFlag) && int.TryParse(queryDic[commonParameters.EncryptFlag].ToString(), out int encryptint))
                {
                    encryptEnum = (EncryptEnum)encryptint;
                }
                //认证token也参与签名
                if (!string.IsNullOrWhiteSpace(request.Request.Headers["Authorization"]))
                {
                    queryDic.Add("authorization", request.Request.Headers["Authorization"]);
                }

                var timestampStr = queryDic[commonParameters.TimestampName];
                if (!long.TryParse(timestampStr, out long timestamp) || !SignCommon.CheckTime(timestamp, verifySignOption.ExpireSeconds))
                {
                    _logger.LogWarning($"方式:[Middleware] {timestampStr}时间戳已过期");
                    return(Tuple.Create <bool, string>(false, "请校准客户端时间后再试"));
                }

                var appIdString = queryDic[commonParameters.AppIdName].ToString();
                if (string.IsNullOrEmpty(appIdString))
                {
                    _logger.LogWarning(@"方式:[Middleware] The request parameter is missing the Ak/Sk appID parameter
                                          VerifySign:{
                                            AppSecret:{
                                            [AppId]:[Secret]
                                                      }}");
                    return(Tuple.Create <bool, string>(false, "服务异常,AppIdName未配置"));
                }

                var signvalue = queryDic[commonParameters.SignName].ToString();
                queryDic.Remove(commonParameters.SignName);

                string bodyValue;
                if (requestCacheData == null || string.IsNullOrEmpty(requestCacheData.Body))
                {
                    bodyValue = await SignCommon.ReadAsStringAsync(request);

                    requestCacheData = new RequestCacheData {
                        Body = bodyValue
                    };
                }
                else
                {
                    bodyValue = requestCacheData.Body;
                }

                if (!string.IsNullOrEmpty(bodyValue) && !"null".Equals(bodyValue))
                {
                    bodyValue = Regex.Replace(bodyValue, @"\s(?=([^""]*""[^""]*"")*[^""]*$)", string.Empty);

                    bodyValue = bodyValue.Replace("\r\n", "").Replace(" : ", ":").Replace("\n  ", "").Replace("\n", "").Replace(": ", ":").Replace(", ", ",");

                    queryDic.Add("body", bodyValue);
                }

                var dicOrder = queryDic.OrderBy(s => s.Key, StringComparer.Ordinal).ToList();

                StringBuilder requestStr = new StringBuilder();
                for (int i = 0; i < dicOrder.Count(); i++)
                {
                    if (i == dicOrder.Count() - 1)
                    {
                        requestStr.Append($"{dicOrder[i].Key}={dicOrder[i].Value}");
                    }
                    else
                    {
                        requestStr.Append($"{dicOrder[i].Key}={dicOrder[i].Value}&");
                    }
                }

                var utf8Request = SignCommon.GetUtf8(requestStr.ToString());



                var result = _verifySignCommon.GetSignhHash(utf8Request, _verifySignCommon.GetSignSecret(appIdString), encryptEnum);
                if (verifySignOption.IsDebug)
                {
                    _logger.LogInformation($"方式:[Middleware] 请求接口地址:{request.Request.Path}");
                    _logger.LogInformation($"方式:[Middleware] 服务器签名前重新排序后的值={Convert.ToBase64String(Encoding.Default.GetBytes(utf8Request))}");
                    _logger.LogInformation($"方式:[Middleware] 摘要比对: 服务器签名结果={result}   客户端签名结果={signvalue };equal={signvalue == result}");
                    _logger.LogInformation($"方式:[Middleware] encryptEnum={encryptEnum}密钥={_verifySignCommon.GetSignSecret(appIdString)}");
                }
                else if (signvalue != result)
                {
                    _logger.LogWarning(@$ "方式:[Middleware] 摘要被篡改:[iphide]----{signvalue }
                                            查看详情,请设置VerifySignOption节点的IsDebug为true");
                    return(Tuple.Create <bool, string>(false, "签名异常,请求非法"));
                }
                return(Tuple.Create <bool, string>(true, "签名通过"));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "方式:[Middleware] 签名异常");
                return(Tuple.Create <bool, string>(false, "签名异常"));
            }
        }
Example #5
0
        private bool GetSignValue(HttpRequest request)
        {
            try
            {
                var queryDic         = request.Query.ToDictionary(s => s.Key, s => s.Value);
                var commonParameters = _verifySignOption.CommonParameters;
                if (!queryDic.ContainsKey(commonParameters.TimestampName) || !queryDic.ContainsKey(commonParameters.AppIdName) || !queryDic.ContainsKey(commonParameters.SignName))
                {
                    _logger.LogError("url参数中未找到签名所需参数[timestamp];[appid]或[sign]");
                    return(false);
                }

                var timestampStr = queryDic[commonParameters.TimestampName];
                if (!long.TryParse(timestampStr, out long timestamp) || !CheckTime(timestamp))
                {
                    _logger.LogError($"{timestampStr}时间戳已过期");
                    return(false);
                }

                var appIdString = queryDic[commonParameters.AppIdName].ToString();
                if (string.IsNullOrEmpty(appIdString))
                {
                    _logger.LogError(@"The request parameter is missing the Ak/Sk appID parameter
                                          VerifySign:{
                                            AppSecret:{
                                            [AppId]:[Secret]
                                                      }}");
                    return(false);
                }

                var signvalue = queryDic[commonParameters.SignName].ToString();
                queryDic.Remove(commonParameters.SignName);

                var bodyValue = SignCommon.ReadAsString(request);
                if (!string.IsNullOrEmpty(bodyValue) && !"null".Equals(bodyValue))
                {
                    var dict = JsonSerializer.Deserialize <Dictionary <string, string> >(bodyValue);
                    foreach (var item in dict)
                    {
                        queryDic.Add(item.Key, item.Value);
                        if (_verifySignOption.IsDebug)
                        {
                            _logger.LogInformation($"字段:{item.Key}--值:{item.Value}");
                        }
                    }
                }
                var dicOrder = queryDic.OrderBy(s => s.Key, StringComparer.Ordinal).ToList();

                StringBuilder requestStr = new StringBuilder();
                for (int i = 0; i < dicOrder.Count(); i++)
                {
                    if (i == dicOrder.Count() - 1)
                    {
                        requestStr.Append($"{dicOrder[i].Key}={dicOrder[i].Value}");
                    }
                    else
                    {
                        requestStr.Append($"{dicOrder[i].Key}={dicOrder[i].Value}&");
                    }
                }

                var utf8Request = SignCommon.GetUtf8(requestStr.ToString());

                var result = _verifySignCommon.GetSignhHash(utf8Request, _verifySignCommon.GetSignSecret(appIdString));
                if (_verifySignOption.IsDebug)
                {
                    _logger.LogInformation($"拼装排序后的值{request.Path}");
                    _logger.LogInformation($"拼装排序后的值{requestStr}");
                    _logger.LogInformation($"摘要计算后的值:{result}");
                    _logger.LogInformation($"摘要比对: {result}----{signvalue }");
                }
                else if (signvalue != result)
                {
                    _logger.LogWarning(@$ "摘要被篡改:[iphide]----{signvalue }
                                            查看详情,请设置VerifySignOption节点的IsDebug为true");
                }
                return(signvalue == result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "签名异常");
                return(false);
            }
        }