public async Task <ServiceResult <object> > Path([FromServices] IServicePartProvider servicePartProvider, string path, [FromBody] Dictionary <string, object> model) { string serviceKey = this.Request.Query["servicekey"]; if (model == null) { model = new Dictionary <string, object>(); } foreach (string n in this.Request.Query.Keys) { model[n] = this.Request.Query[n].ToString(); } ServiceResult <object> result = ServiceResult <object> .Create(false, null); path = path.ToLower() == GateWayAppConfig.TokenEndpointPath.ToLower() ? GateWayAppConfig.AuthorizationRoutePath : path.ToLower(); if (servicePartProvider.IsPart(path)) { result = ServiceResult <object> .Create(true, await servicePartProvider.Merge(path, model)); result.StatusCode = (int)ServiceStatusCode.Success; } else if (OnAuthorization(path, model, ref result)) { if (path == GateWayAppConfig.AuthorizationRoutePath) { var token = await _authorizationServerProvider.GenerateTokenCredential(model); if (token != null) { result = ServiceResult <object> .Create(true, token); result.StatusCode = (int)ServiceStatusCode.Success; } else { result = new ServiceResult <object> { IsSucceed = false, StatusCode = (int)ServiceStatusCode.AuthorizationFailed, Message = "Invalid authentication credentials" }; } } else { if (!string.IsNullOrEmpty(serviceKey)) { result = ServiceResult <object> .Create(true, await _serviceProxyProvider.Invoke <object>(model, path, serviceKey)); result.StatusCode = (int)ServiceStatusCode.Success; } else { result = ServiceResult <object> .Create(true, await _serviceProxyProvider.Invoke <object>(model, path)); result.StatusCode = (int)ServiceStatusCode.Success; } } } return(result); }
public async Task <OAuthUser> GenerateTokenCredential(Dictionary <string, object> parameters) { OAuthUser oAuthUser = new OAuthUser() { IsSucceed = false }; string result = null; var payload = await _serviceProxyProvider.Invoke <object>(parameters, AppConfig.AuthorizationRoutePath, AppConfig.AuthorizationServiceKey); if (payload != null && !payload.Equals("null")) { oAuthUser = JsonConvert.DeserializeObject <OAuthUser>(payload.ToString()); if (oAuthUser.IsSucceed) { var jwtHeader = JsonConvert.SerializeObject(new JWTSecureDataHeader() { TimeStamp = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") }); var base64Payload = ConverBase64String(JsonConvert.SerializeObject(payload)); var encodedString = $"{ConverBase64String(jwtHeader)}.{base64Payload}"; var route = await _serviceRouteProvider.GetRouteByPath(AppConfig.AuthorizationRoutePath); var signature = HMACSHA256(encodedString, route.ServiceDescriptor.Token); result = $"{encodedString}.{signature}"; oAuthUser.AccessToken = result; oAuthUser.ExpireTime = AppConfig.AccessTokenExpireTimeSpan.TotalSeconds; _cacheProvider.Add(base64Payload, result, AppConfig.AccessTokenExpireTimeSpan); } } return(oAuthUser); }
/// <summary> /// Merges the specified routh path. /// </summary> /// <param name="routhPath">The routh path.</param> /// <param name="param">The parameter.</param> /// <returns>Task<System.Object>.</returns> public async Task <object> Merge(string routhPath, Dictionary <string, object> param) { var partType = _servicePartTypes.GetValueOrDefault(routhPath); var jObject = new JObject(); if (partType == ServicePartType.Main) { param.TryGetValue("ServiceAggregation", out var model); var parts = model as JArray; foreach (var part in parts) { var routeParam = part["Params"].ToObject <Dictionary <string, object> >(); var path = part.Value <string>("RoutePath"); var serviceKey = part.Value <string>("ServiceKey"); var result = await _serviceProxyProvider.Invoke <object>(routeParam, path, serviceKey); jObject.Add(part.Value <string>("Key"), JToken.FromObject(result)); } } else { var service = AppConfig.ServicePart.Services .Where(p => p.UrlMapping.Equals(routhPath, StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); foreach (var part in service.serviceAggregation) { var result = await _serviceProxyProvider.Invoke <object>(param, part.RoutePath, part.ServiceKey); jObject.Add(part.Key, JToken.FromObject(result)); } ; } return(jObject); }
public async Task <string> GenerateTokenCredential(LoginInput input) { var rpcParams = new Dictionary <string, object>() { { "input", new { input.UserName, input.Password } } }; var loginResult = await _serviceProxyProvider.Invoke <LoginResult>(rpcParams, AppConfig.AuthenticationRoutePath, AppConfig.AuthenticationServiceKey); if (loginResult.ResultType == LoginResultType.Fail) { throw new AuthException(loginResult.ErrorMessage); } if (loginResult.ResultType == LoginResultType.Error) { throw new BusinessException(loginResult.ErrorMessage); } var jwtHader = new Dictionary <string, object>() { { "timeStamp", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") }, { "typ", "JWT" }, { "alg", AppConfig.JwtConfig.EncryptionAlgorithm } }; var payload = loginResult.PayLoad; payload.Add("iss", AppConfig.JwtConfig.Iss); payload.Add("aud", AppConfig.JwtConfig.Aud); payload.Add("iat", DateTime.Now); payload.Add("exp", DateTime.Now.AddMinutes(AppConfig.JwtConfig.Period)); //payload.Add("ast", accessSystemType); return(_jwtTokenProvider.GenerateToken(jwtHader, payload, AppConfig.JwtConfig.SecretKey, AppConfig.JwtConfig.EncryptionAlgorithm)); }
public async Task <string> Path(string path, [FromQuery] string serviceKey, [FromBody] Dictionary <string, object> model) { string result = ""; if (!string.IsNullOrEmpty(serviceKey)) { result = await _serviceProxyProvider.Invoke <string>(model, path, serviceKey); } else { result = await _serviceProxyProvider.Invoke <string>(model, path); } return(result); }
public async Task <string> IssueToken(Dictionary <string, object> parameters) { string result = null; var payload = await _serviceProxyProvider.Invoke <IDictionary <string, object> >(parameters, AppConfig.AuthenticationRoutePath, HttpMethod.POST, AppConfig.AuthenticationServiceKey); if (payload != null && !payload.Equals("null")) { if (!payload.ContainsKey(ClaimTypes.UserId) || !payload.ContainsKey(ClaimTypes.UserName)) { throw new AuthException($"认证接口实现不正确,接口返回值必须包含{ClaimTypes.UserId}和{ClaimTypes.UserName}的声明"); } var jwtBuilder = GetJwtBuilder(AppConfig.JwtSecret); var exp = AppConfig.DefaultExpired; if (payload.ContainsKey(ClaimTypes.Expired)) { exp = payload[ClaimTypes.Expired].To <int>(); payload.Remove(ClaimTypes.Expired); } jwtBuilder.AddClaim(ClaimTypes.Expired, DateTimeOffset.UtcNow.AddHours(exp).ToUnixTimeSeconds()); foreach (var para in payload) { jwtBuilder.AddClaim(para.Key, para.Value); } result = jwtBuilder.Encode(); } return(result); }
/// <summary> /// 按钮上的广告 /// 重庆时时彩 加奖92% ★★★奖金★★★ /// 竞猜足球 加奖12%(红包) /// 江西11选5,加奖60% ★★奖金★★ /// 竞猜篮球 加奖15%(红包) /// 胜负彩 加奖15% (红包) /// </summary> /// <returns></returns> public async Task <IActionResult> GameInfoIndex([FromServices] IServiceProxyProvider _serviceProxyProvider) { //var APP_Advertising_Key = "APP_Advertising_V2"; //var APP_Advertising_Value = await GetAppConfigByKey(_serviceProxyProvider, APP_Advertising_Key); //if (string.IsNullOrEmpty(APP_Advertising_Value)) //{ // var APP_AdList = JsonHelper.Deserialize<APP_Advertising>(APP_Advertising_Value); // var //} try { var GameAdList = await _serviceProxyProvider.Invoke <List <APP_Advertising> >(new Dictionary <string, object>(), "api/Data/GetGameInfoIndex"); return(Json(new LotteryServiceResponse { Code = ResponseCode.成功, Message = "查询按钮广告成功", MsgId = "", Value = GameAdList })); } catch (Exception ex) { return(Json(new LotteryServiceResponse { Code = ResponseCode.失败, Message = "查询按钮广告失败" + "●" + ex.ToString(), MsgId = "", Value = ex.ToGetMessage() })); } }
private async Task <HttpResultMessage <object> > RemoteExecuteAsync(HttpMessage httpMessage) { HttpResultMessage <object> resultMessage = new HttpResultMessage <object>(); try { var entity = await _serviceProxyProvider.Invoke <Object>(httpMessage.Parameters, httpMessage.RoutePath, httpMessage.ServiceKey); if (entity != null) { entity = JsonConvert.DeserializeObject(entity.ToString(), typeof(Object)); } resultMessage.Entity = entity; resultMessage.IsSucceed = resultMessage.Entity != default; resultMessage.StatusCode = resultMessage.IsSucceed ? (int)StatusCode.Success : (int)StatusCode.RequestError; } catch (Exception ex) { if (_logger.IsEnabled(LogLevel.Error)) { _logger.LogError(ex, "执行远程调用逻辑时候发生了错误。"); } resultMessage = new HttpResultMessage <object> { Entity = null, Message = "执行发生了错误。", StatusCode = (int)StatusCode.RequestError }; } return(resultMessage); }
private async Task <HttpResultMessage <object> > RemoteExecuteAsync(HttpRequestMessage httpMessage) { var resultMessage = new HttpResultMessage <object>(); try { resultMessage.Result = await _serviceProxyProvider.Invoke <object>(httpMessage.Parameters, httpMessage.RoutePath, httpMessage.ServiceKey); resultMessage.IsSucceed = resultMessage.Result != default; resultMessage.StatusCode = resultMessage.IsSucceed ? (int)StatusCode.Success : (int)StatusCode.RequestError; } catch (Exception exception) { if (_logger.IsEnabled(LogLevel.Error)) { _logger.LogError(exception, $"执行远程调用逻辑时候发生了错误:{exception.Message}"); } resultMessage.Result = null; resultMessage.StatusCode = (int)StatusCode.RequestError; resultMessage.Message = "执行发生了错误。"; resultMessage.Message = ExceptionPrompt.GetPrompt(exception); } return(resultMessage); }
public async Task <IActionResult> NumLettory_WinNumber_Start([FromServices] IServiceProxyProvider _serviceProxyProvider, string address, string queryParam) { var param = new Dictionary <string, object>(); param.Add("gameName", "CQSSC"); var config = await _serviceProxyProvider.Invoke <string>(param, "creawser/craw/numlettory_winnumber_start"); return(Json(new { config = config })); }
public async Task <ServiceResult <object> > Post(string path, string serviceKey, Dictionary <string, object> model) { model = model ?? new Dictionary <string, object>(); ServiceResult <object> result = ServiceResult <object> .Create(false, null); path = string.IsNullOrEmpty(path) ? GateWayAppConfig.AuthorizationRoutePath : path.ToLower(); if (OnAuthorization(path, model, ref result)) { if (path == GateWayAppConfig.AuthorizationRoutePath) { var token = await _authorizationServerProvider.GenerateTokenCredential(model); if (token != null) { result = ServiceResult <object> .Create(true, token); result.StatusCode = (int)ServiceStatusCode.Success; } else { result = new ServiceResult <object> { IsSucceed = false, StatusCode = (int)ServiceStatusCode.AuthorizationFailed, Message = "Invalid authentication credentials" }; } } else { if (!string.IsNullOrEmpty(serviceKey)) { result = ServiceResult <object> .Create(true, await _serviceProxyProvider.Invoke <object>(model, path, serviceKey)); result.StatusCode = (int)ServiceStatusCode.Success; } else { result = ServiceResult <object> .Create(true, await _serviceProxyProvider.Invoke <object>(model, path)); result.StatusCode = (int)ServiceStatusCode.Success; } } } return(result); }
/// <summary> /// 通过路由调用服务 /// </summary> /// 调试 http://127.0.0.1:729/api/Home/GetServiceByRouter api/User/GetUser /// <param name="serviceDiscoveryProvider"></param> /// <param name="address"></param> /// <param name="queryParam"></param> /// <returns></returns> public async Task <IActionResult> GetServiceByRouter([FromServices] IServiceProxyProvider _serviceProxyProvider, string address = "api/user/GetUserList") { Dictionary <string, object> model = new Dictionary <string, object>(); model["userName"] = "******"; var sdt = DateTime.Now; var result = await _serviceProxyProvider.Invoke <object>(model, address); var edt = DateTime.Now; return(Json(new { result = result, s = sdt.ToString("HH:mm:ss ffff"), e = edt.ToString("HH:mm:ss ffff") })); }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now); _queue.TryDequeue(out Message message); if (message != null) { var result = await _serviceProxyProvider.Invoke <object>(message.Parameters, message.RoutePath, message.ServiceKey); _logger.LogInformation("Invoke Service at: {time}", DateTimeOffset.Now); } await Task.Delay(1000, stoppingToken); }
public async Task <string> SayHello(string name) { //GetService<IUserService>("User").GetUserId("fanly"); Dictionary <string, object> model = new Dictionary <string, object>(); model.Add("name", name); string path = "api/hello/say"; string result = await _serviceProxyProvider.Invoke <string>(model, path, null); return(result); }
public async Task <ServiceResult <object> > Path(string path, [FromQuery] string serviceKey, [FromBody] Dictionary <string, object> model) { ServiceResult <object> result = ServiceResult <object> .Create(false, null); if (OnAuthorization(path, model, ref result)) { if (!string.IsNullOrEmpty(serviceKey)) { result = ServiceResult <object> .Create(true, await _serviceProxyProvider.Invoke <object>(model, path, serviceKey)); result.StatusCode = (int)ServiceStatusCode.Success; } else { result = ServiceResult <object> .Create(true, await _serviceProxyProvider.Invoke <object>(model, path)); result.StatusCode = (int)ServiceStatusCode.Success; } } return(result); }
public async Task <string> GenerateTokenCredential(IDictionary <string, object> rpcParams) { LoginResult loginResult; if (AppConfig.AuthorizationServiceKey.IsNullOrEmpty()) { loginResult = await _serviceProxyProvider.Invoke <LoginResult>(rpcParams, AppConfig.AuthenticationRoutePath); } else { loginResult = await _serviceProxyProvider.Invoke <LoginResult>(rpcParams, AppConfig.AuthenticationRoutePath, AppConfig.AuthenticationServiceKey); } if (loginResult == null) { throw new BusinessException("当前系统无法登陆,请稍后重试"); } if (loginResult.ResultType == LoginResultType.Fail) { throw new AuthException(loginResult.ErrorMessage); } if (loginResult.ResultType == LoginResultType.Error) { throw new BusinessException(loginResult.ErrorMessage); } var jwtHader = new Dictionary <string, object>() { { "timeStamp", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") }, { "typ", "JWT" }, { "alg", AppConfig.JwtConfig.EncryptionAlgorithm } }; var payload = loginResult.PayLoad; payload.Add("iss", AppConfig.JwtConfig.Iss); payload.Add("aud", AppConfig.JwtConfig.Aud); payload.Add("iat", DateTime.Now); payload.Add("exp", DateTime.Now.AddMinutes(AppConfig.JwtConfig.Period)); //payload.Add("ast", accessSystemType); return(_jwtTokenProvider.GenerateToken(jwtHader, payload, AppConfig.JwtConfig.SecretKey, AppConfig.JwtConfig.EncryptionAlgorithm)); }
public async Task CreateUserInfo(UserInfo userInfo) { var rpcParams = new Dictionary <string, object>() { { "confName", IdentityConstants.SysConfPwdModeName } }; var pwdConfig = await _serviceProxyProvider.Invoke <GetSystemConfOutput>(rpcParams, ApiConsts.BasicData.GetSysConfApi); if (pwdConfig == null) { throw new BusinessException("获取用户加密模式失败,请先完成系统初始化"); } var generatePwdMode = ConvertHelper.ParseEnum <GeneratePwdMode>(pwdConfig.ConfigValue); var plainPwd = string.Empty; if (generatePwdMode == GeneratePwdMode.Fixed) { rpcParams = new Dictionary <string, object>() { { "confName", IdentityConstants.SysConfFieldModeName } }; var fixedPwdConf = await _serviceProxyProvider.Invoke <GetSystemConfOutput>(rpcParams, ApiConsts.BasicData.GetSysConfApi); if (pwdConfig == null) { throw new BusinessException("未配置员工用户默认密码"); } plainPwd = fixedPwdConf.ConfigValue; } else { plainPwd = PasswordGenerator.GetRandomPwd(IdentityConstants.RandomLen); // :todo email send pwd } userInfo.Password = _passwordHelper.EncryptPassword(userInfo.UserName, plainPwd); await _userRepository.InsertAsync(userInfo); }
/// <summary> /// 生成TOKEN凭证 /// </summary> /// <param name="parameters">字典参数</param> /// <param name="accessSystemType"></param> /// <returns></returns> public async Task <string> GenerateTokenCredential(Dictionary <string, object> parameters, AccessSystemType accessSystemType = AccessSystemType.Inner) { string result = null; var tokenEndpointPath = accessSystemType == AccessSystemType.Inner ? AppConfig.AuthenticationRoutePath : AppConfig.ThirdPartyAuthenticationRoutePath; var payload = await _serviceProxyProvider.Invoke <object>(parameters, tokenEndpointPath, AppConfig.AuthorizationServiceKey); if (payload != null && !payload.Equals("null")) { var jwtHeader = JsonConvert.SerializeObject(new JWTSecureDataHeader() { TimeStamp = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") }); var base64Payload = ConverBase64String(JsonConvert.SerializeObject(payload)); var encodedString = $"{ConverBase64String(jwtHeader)}.{base64Payload}"; var route = await _serviceRouteProvider.GetRouteByPath(tokenEndpointPath); var signature = HMACSHA256(encodedString, route.ServiceDescriptor.Token); result = $"{encodedString}.{signature}"; _cacheProvider.Add(base64Payload, result, AppConfig.AccessTokenExpireTimeSpan); } return(result); }
public async Task <bool> Authorize(string apiPath, Dictionary <string, object> parameters) { var route = await _serviceRouteProvider.GetRouteByPath(apiPath); //if (AppConfig.WhiteList.Contains(apiPath)) //{ // return true; //} if (route.ServiceDescriptor.AllowPermission()) { return(true); } return(await _serviceProxyProvider.Invoke <bool>(parameters, AppConfig.SwaggerOptions.Authorization.AuthorizationRoutePath, AppConfig.SwaggerOptions.Authorization.AuthorizationServiceKey ?? "")); }
/// <summary> /// Kson 获取日志 /// </summary> /// <param name="_serviceProxyProvider"></param> /// <param name="SerName"></param> /// <param name="FileName"></param> /// <returns></returns> public async Task <IActionResult> GetTimeLog([FromServices] IServiceProxyProvider _serviceProxyProvider, string SerName = "Order", string FileName = "") { string config = ""; if (SerName.ToLower() == "api") { config = KaSon.FrameWork.Common.Utilities.FileHelper.GetLogInfo("Log_Log\\APITimeInfo", "LogTime_"); } else { Dictionary <string, object> param = new Dictionary <string, object>(); param.Add("FileName", FileName); config = await _serviceProxyProvider.Invoke <string>(param, "api/" + SerName + "/ReadSqlTimeLog"); } config = string.IsNullOrEmpty(config) ? "没有数据" : config; return(Content(config)); }
public async Task <IActionResult> GetAPP_shareScheme([FromServices] IServiceProxyProvider _serviceProxyProvider, LotteryServiceRequest entity) { try { var p = JsonHelper.Decode(entity.Param); string userToken = p.UserToken; if (string.IsNullOrEmpty(userToken)) { throw new Exception("参数不能为空"); } string userid = KaSon.FrameWork.Common.CheckToken.UserAuthentication.ValidateAuthentication(userToken); Dictionary <string, object> param = new Dictionary <string, object>(); param["userId"] = userid; var bindInfo = await _serviceProxyProvider.Invoke <LoginInfo>(param, "api/user/GetLocalLoginByUserId"); var key = ""; if (bindInfo != null && bindInfo.IsAgent) { key = "APP_shareScheme_Pid"; } else { key = "APP_shareScheme_Fxid"; } var value = await GetAppConfigByKey(_serviceProxyProvider, key); return(Json(new LotteryServiceResponse { Code = ResponseCode.成功, Message = "查询配置成功", MsgId = entity.MsgId, Value = JsonHelper.Deserialize <object>(value) })); } catch (Exception ex) { return(Json(new LotteryServiceResponse { Code = ResponseCode.失败, Message = "查询配置失败" + "●" + ex.ToString(), MsgId = entity.MsgId, Value = ex.ToGetMessage() })); } }
/// <summary> /// 获取app相关配置 /// </summary> private async Task <string> GetAppConfigByKey([FromServices] IServiceProxyProvider _serviceProxyProvider, string key, string defalutValue = "") { try { //1.从redis中取 //2.取不到则在sql中取 //3.不为空则存入redis中,3分钟缓存 //var flag = KaSon.FrameWork.Common.Redis.RedisHelperEx.KeyExists(key); //var v = ""; //if (flag) //{ // v = KaSon.FrameWork.Common.Redis.RedisHelperEx.StringGet(key); //} //if (string.IsNullOrEmpty(v)) //{ // var param = new Dictionary<string, object>(); // param.Add("key", key); // var config = await _serviceProxyProvider.Invoke<C_Core_Config>(param, "api/Data/QueryCoreConfigByKey"); // if (config != null) // { // v = config.ConfigValue; // KaSon.FrameWork.Common.Redis.RedisHelperEx.StringSet(key, config.ConfigValue, 3 * 60); // } // if (string.IsNullOrEmpty(v)) // { // return defalutValue; // } //} //return v; var param = new Dictionary <string, object>(); param.Add("key", key); var config = await _serviceProxyProvider.Invoke <C_Core_Config>(param, "api/Data/QueryCoreConfigByKey"); if (config != null) { return(config.ConfigValue); } return(defalutValue); } catch (Exception) { return(defalutValue); } }
public static void TestForRoutePath(IServiceProxyProvider serviceProxyProvider) { Dictionary <string, object> model = new Dictionary <string, object>(); model.Add("user", JsonConvert.SerializeObject(new { Name = "fanly", Age = 18, UserId = 1 })); string path = "api/user/getuser"; string serviceKey = "User"; var userProxy = serviceProxyProvider.Invoke <object>(model, path, serviceKey); var s = userProxy.Result; Console.WriteLine("Press any key to exit..."); Console.ReadLine(); }
private async Task <HttpResultMessage <object> > RemoteExecuteAsync(HttpMessage httpMessage) { HttpResultMessage <object> resultMessage = new HttpResultMessage <object>(); try { resultMessage.Entity = await _serviceProxyProvider.Invoke <object>(httpMessage.Parameters, httpMessage.RoutePath, httpMessage.ServiceKey); resultMessage.IsSucceed = resultMessage.Entity != default; resultMessage.StatusCode = resultMessage.IsSucceed ? (int)StatusCode.Success : (int)StatusCode.RequestError; } catch (Exception ex) { resultMessage = new HttpResultMessage <object> { Entity = null, Message = "执行发生了错误。", StatusCode = (int)StatusCode.RequestError }; } return(resultMessage); }
public static void TestForRoutePath(IServiceProxyProvider serviceProxyProvider) { Dictionary <string, object> model = new Dictionary <string, object>(); model.Add("user", new UserModel { Name = "fanly", Age = 12, UserId = 2, Sex = Sex.Woman }); string path = "api/user/getuser"; string serviceKey = "User"; var userProxy = serviceProxyProvider.Invoke <UserModel>(model, path, serviceKey); var s = userProxy.Result; Console.WriteLine("Press any key to exit..."); Console.ReadLine(); }
private async Task <HttpResultMessage <object> > RemoteExecuteAsync(HttpMessage httpMessage) { HttpResultMessage <object> resultMessage = new HttpResultMessage <object>(); try { resultMessage.Data = await _serviceProxyProvider.Invoke <object>(httpMessage.Parameters, httpMessage.RoutePath, httpMessage.ServiceKey); resultMessage.IsSucceed = resultMessage.Data != default; resultMessage.StatusCode = resultMessage.IsSucceed ? (int)StatusCode.Success : (int)StatusCode.RequestError; } catch (Exception ex) { if (_logger.IsEnabled(LogLevel.Error)) { _logger.LogError(ex, "执行远程调用逻辑时候发生了错误。"); } resultMessage = new HttpResultMessage <object> { Data = null, Message = "执行发生了错误。", StatusCode = (int)StatusCode.RequestError }; } return(resultMessage); }
public async Task <string> GenerateTokenCredential(Dictionary <string, object> parameters) { string result = null; var payload = await _serviceProxyProvider.Invoke <object>(parameters, AppConfig.AuthorizationRoutePath, AppConfig.AuthorizationServiceKey); if (payload != null) { var jwtHeader = JsonConvert.SerializeObject(new JWTSecureDataHeader() { TimeStamp = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") }); var base64Payload = ConverBase64String(JsonConvert.SerializeObject(payload)); var encodedString = $"{ConverBase64String(jwtHeader)}.{base64Payload}"; var route = await _serviceRouteProvider.GetRouteByPath(AppConfig.AuthorizationRoutePath); var addressModel = route.Address.FirstOrDefault(); var signature = HMACSHA256(encodedString, addressModel.Token); result = $"{encodedString}.{signature}"; _cacheProvider.Add(base64Payload, result, AppConfig.AccessTokenExpireTimeSpan); } return(result); }
public async Task <string> GenerateTokenCredential(Dictionary <string, object> parameters) { var payload = await _serviceProxyProvider.Invoke <object>(parameters, GatewayConfig.AuthorizationRoutePath, GatewayConfig.AuthorizationServiceKey); if (payload == null || payload.Equals("null")) { return(null); } var jwtHeader = JsonConvert.SerializeObject(new JwtSecureDataHeader { TimeStamp = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") }); var base64Payload = ConverBase64String(JsonConvert.SerializeObject(payload)); var encodedString = $"{ConverBase64String(jwtHeader)}.{base64Payload}"; var route = await _serviceRouteProvider.GetRouteByPath(GatewayConfig.AuthorizationRoutePath); var signature = HMACSHA256(encodedString, route.ServiceDescriptor.Token); var result = $"{encodedString}.{signature}"; _cacheProvider.Add(base64Payload, result, GatewayConfig.AccessTokenExpireTimeSpan); return(result); }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { try { _token = stoppingToken; _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now); _queue.TryDequeue(out Message message); if (message != null) { var result = await _serviceProxyProvider.Invoke <object>(message.Parameters, message.RoutePath, message.ServiceKey); _logger.LogInformation("Invoke Service at: {time},Invoke result:{result}", DateTimeOffset.Now, result); } if (!_token.IsCancellationRequested) { await Task.Delay(1000, stoppingToken); } } catch (Exception ex) { _logger.LogError("WorkService execute error, message:{message} ,trace info:{trace} ", ex.Message, ex.StackTrace); } }
private async Task <HttpResultMessage <object> > RemoteExecuteAsync(HttpMessage httpMessage) { HttpResultMessage <object> resultMessage = new HttpResultMessage <object>(); try { var resultData = await _serviceProxyProvider.Invoke <object>(httpMessage.Parameters, httpMessage.RoutePath, httpMessage.ServiceKey); resultMessage.Entity = HandleResultData(resultData); resultMessage.IsSucceed = resultMessage.Entity != default; resultMessage.StatusCode = resultMessage.IsSucceed ? StatusCode.Success : StatusCode.RequestError; } catch (Exception ex) { if (_logger.IsEnabled(LogLevel.Error)) { _logger.LogError(ex, "执行远程调用逻辑时候发生了错误。"); } resultMessage = new HttpResultMessage <object> { Entity = null, Message = ex.GetExceptionMessage(), StatusCode = ex.GetGetExceptionStatusCode() }; } return(resultMessage); }