Example #1
0
        /// <summary>
        ///     在调用操作方法之前发生。
        /// </summary>
        /// <param name="actionContext">操作上下文。</param>
        public override async System.Threading.Tasks.Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            // 判断是否忽略验证
            if (context.ActionDescriptor is ControllerActionDescriptor cad)
            {
                var controleIgnor = cad.ControllerTypeInfo.GetCustomAttributes(inherit: true).Any(x => x is IgnorValidateSignatureAttribute || x is InnerServiceAttribute || x is AllowAnonymousAttribute);
                if (controleIgnor)
                {
                    return;
                }
                var actionIgnor = cad.MethodInfo.GetCustomAttributes(inherit: true).Any(x => x is IgnorValidateSignatureAttribute || x is InnerServiceAttribute || x is AllowAnonymousAttribute);
                if (actionIgnor)
                {
                    return;
                }
            }
            ApiResultModel <string> apiResult = null;
            HttpRequest             request   = context.HttpContext.Request;

            #region 票据

            string ticket = "";
            var    secret = "";
            if (context.RouteData.Values["Action"].ToString().ToLower() != "getappticket")
            {
                if (request.Headers.ContainsKey(TicketKey))
                {
                    ticket = request.Headers[TicketKey].ToString();
                    var redisKey  = RedisCommon.GetTicketKey(ticket);
                    var redisData = RedisClient.Get <AppTicketModel>(RedisDatabase.DB_AuthorityService, redisKey);
                    if (redisData == null)
                    {
                        apiResult = new ApiResultModel <string>()
                        {
                            Code = ApiResultCode.TicketInvalid
                        };
                        context.Result = new JsonResult(apiResult);
                        return;
                    }
                    secret = redisData.AppSecret;
                }
                else
                {
                    apiResult = new ApiResultModel <string>()
                    {
                        Code = ApiResultCode.NoTicket
                    };
                    context.Result = new JsonResult(apiResult);
                    return;
                }
            }
            else
            {
                secret = AppSettingsHelper.Configuration["ApiConfig:SignDefaultKey"];//生成票据时,签名用默认key
            }

            #endregion

            #region  签名

            Dictionary <string, object> dictionary = null;

            if (request.Method == "POST")
            {
                if (request.ContentLength > 0)
                {
                    request.Body.Position = 0;
                    Stream stream = request.Body;
                    byte[] buffer = new byte[request.ContentLength.Value];
                    stream.Read(buffer, 0, buffer.Length);

                    var bodyStr = Encoding.UTF8.GetString(buffer);
                    dictionary = JsonHelper.DeserializeObject <Dictionary <string, object> >(bodyStr);
                }
            }
            else
            {
                dictionary = new Dictionary <string, object>(context.ActionArguments);
            }

            if (!dictionary.ContainsKey(SignKey))//参数不包含签名
            {
                apiResult = new ApiResultModel <string>()
                {
                    Code = ApiResultCode.NoSign
                };
                context.Result = new JsonResult(apiResult);
                return;
            }
            else if (!dictionary.ContainsKey(TimestampKey))//参数不包含时间戳
            {
                apiResult = new ApiResultModel <string>()
                {
                    Code = ApiResultCode.NoTimestamp
                };
                context.Result = new JsonResult(apiResult);
                return;
            }

            var keys = dictionary.Keys.ToList();
            foreach (var key in keys)
            {
                //参数为集合类型
                var value = dictionary[key];
                if (value != null && value.GetType().Namespace == "Newtonsoft.Json.Linq")
                {
                    dictionary[key] = JsonHelper.SerializeObject(value);
                }
            }

            //验证签名
            apiResult = ValidateSignature(dictionary, secret);
            if (apiResult.Code != ApiResultCode.Success)
            {
                context.Result = new JsonResult(apiResult);
                return;
            }

            #endregion

            await base.OnActionExecutionAsync(context, next);
        }
Example #2
0
        /// <summary>
        /// 生成票据
        /// </summary>
        /// <param name="requestModel"></param>
        /// <returns></returns>
        public ApiResultModel <AddAppTicketResponseModel> GetAppTicket(AddAppTicketRequestModel requestModel)
        {
            var result = new ApiResultModel <AddAppTicketResponseModel>()
            {
                Message = "生成票据失败"
            };

            if (requestModel.AppId.IsNullOrEmpty())
            {
                result.Message = "AppId不能为空";
                return(result);
            }
            if (requestModel.DeviceNo.IsNullOrEmpty())
            {
                result.Message = "客户端设备号不能为空";
                return(result);
            }
            var clentType  = requestModel.ClientType.GetEnumDescription();
            var nonce      = Utils.GetNonce();
            var ticket     = AuthenticationHelper.GetTicket(requestModel.AppId, clentType, requestModel.DeviceNo, nonce);
            var secret     = AuthenticationHelper.GetAppSecret(requestModel.AppId, clentType, requestModel.DeviceNo, nonce);
            var resultData = new AddAppTicketResponseModel()
            {
                Ticket    = ticket,
                AppSecret = secret
            };
            AppTicket model = _db.AppTicket.FirstOrDefault(x => x.AppId == requestModel.AppId && x.ClientType == clentType && x.DeviceNo == requestModel.DeviceNo);

            if (model == null)
            {
                model = new AppTicket()
                {
                    Id             = GuidTool.GetGuid(),
                    AppId          = requestModel.AppId,
                    ClientType     = clentType,
                    DeviceNo       = requestModel.DeviceNo,
                    Noncestr       = nonce,
                    AppSecret      = secret,
                    Ticket         = ticket,
                    LastUpdateTime = DateTime.Now
                };
                _db.AppTicket.Add(model);
                _db.Entry(model).State = EntityState.Added;
                _db.SaveChanges();
            }
            else
            {
                model.Noncestr       = nonce;
                model.AppSecret      = secret;
                model.Ticket         = ticket;
                model.LastUpdateTime = DateTime.Now;

                _db.AppTicket.Attach(model);
                _db.Entry(model).Property(x => x.Noncestr).IsModified       = true;
                _db.Entry(model).Property(x => x.AppSecret).IsModified      = true;
                _db.Entry(model).Property(x => x.Ticket).IsModified         = true;
                _db.Entry(model).Property(x => x.LastUpdateTime).IsModified = true;
                _db.SaveChanges();
            }

            //缓存
            var redisKey  = RedisCommon.GetTicketKey(ticket);
            var redisData = model.MapTo <AppTicketModel>();

            RedisClient.Set(RedisDatabase.DB_AuthorityService, redisKey, redisData, 60);//1小时

            result.Data = resultData;
            result.Code = ApiResultCode.Success;
            return(result);
        }