Esempio n. 1
0
        public async Task <T> Invoke <T>(IDictionary <string, object> parameters, string routePath)
        {
            var serviceRoute = await _serviceRouteProvider.GetRouteByPath(routePath.ToLower());

            T result = default(T);

            if (parameters.ContainsKey("serviceKey"))
            {
                var serviceKey = parameters["serviceKey"].ToString();
                var proxy      = ServiceResolver.Current.GetService <RemoteServiceProxy>(serviceKey);
                if (proxy == null)
                {
                    proxy = new RemoteServiceProxy(serviceKey.ToString(), _serviceProvider);
                    ServiceResolver.Current.Register(serviceKey.ToString(), proxy);
                }
                result = await proxy.Invoke <T>(parameters, serviceRoute.ServiceDescriptor.Id);
            }
            else
            {
                var proxy = ServiceResolver.Current.GetService <RemoteServiceProxy>();
                if (proxy == null)
                {
                    proxy = new RemoteServiceProxy(null, _serviceProvider);
                    ServiceResolver.Current.Register(null, proxy);
                }
                result = await proxy.Invoke <T>(parameters, serviceRoute.ServiceDescriptor.Id);
            }
            return(result);
        }
Esempio n. 2
0
        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);
        }
Esempio n. 3
0
        private async Task <bool> GetAllowRequest(string path)
        {
            bool isSuccess = true;
            var  route     = await _serviceRouteProvider.GetRouteByPath(path);

            return(!route.ServiceDescriptor.DisableNetwork());
        }
        /// <summary>
        /// Called when [action executing].
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        public async Task OnActionExecuting(ActionExecutingContext filterContext)
        {
            var serviceEntry = _serviceEntryLocate.Locate(filterContext.Message);

            if (serviceEntry != null)
            {
                var httpMethods = serviceEntry.Methods;
                if (httpMethods.Count() > 0 &&
                    !httpMethods.Any(p => string.Compare(p, filterContext.Context.Request.Method, true) == 0))
                {
                    filterContext.Result = new HttpResultMessage <object>
                    {
                        IsSucceed  = false,
                        StatusCode = Http405EndpointStatusCode,
                        Message    = Http405EndpointDisplayName
                    };
                }
            }
            else
            {
                var serviceRoute = await _serviceRouteProvider.GetRouteByPath(filterContext.Message.RoutePath);

                var httpMethods = serviceRoute.ServiceDescriptor.HttpMethod();
                if (!string.IsNullOrEmpty(httpMethods) && !httpMethods.Contains(filterContext.Context.Request.Method))
                {
                    filterContext.Result = new HttpResultMessage <object>
                    {
                        IsSucceed  = false,
                        StatusCode = Http405EndpointStatusCode,
                        Message    = Http405EndpointDisplayName
                    };
                }
            }
        }
Esempio n. 5
0
        private bool OnAuthorization(string path, Dictionary <string, object> model, ref ServiceResult <object> result)
        {
            bool     isSuccess = true;
            var      author    = HttpContext.Request.Headers["Authorization"];
            DateTime time;
            var      routes = _serviceRouteProvider.GetRouteByPath(path).Result;

            if (routes.ServiceDescriptor.EnableAuthorization())
            {
                if (routes.Address.Any(p => p.DisableAuth == false))
                {
                    if (!string.IsNullOrEmpty(path) && model.ContainsKey("timeStamp"))
                    {
                        if (DateTime.TryParse(model["timeStamp"].ToString(), out time))
                        {
                            var seconds = (DateTime.Now - time).TotalSeconds;
                            if (seconds <= 3560 && seconds >= 0)
                            {
                                if (!routes.Address.Any(p => GetMD5($"{p.Token}{time.ToString("yyyy-MM-dd hh:mm:ss") }") == author.ToString()))
                                {
                                    result = new ServiceResult <object> {
                                        IsSucceed = false, StatusCode = (int)ServiceStatusCode.AuthorizationFailed, Message = "Invalid authentication credentials"
                                    };
                                    isSuccess = false;
                                }
                            }
                            else
                            {
                                result = new ServiceResult <object> {
                                    IsSucceed = false, StatusCode = (int)ServiceStatusCode.AuthorizationFailed, Message = "Invalid authentication credentials"
                                };
                                isSuccess = false;
                            }
                        }
                        else
                        {
                            result = new ServiceResult <object> {
                                IsSucceed = false, StatusCode = (int)ServiceStatusCode.AuthorizationFailed, Message = "Invalid authentication credentials"
                            };
                            isSuccess = false;
                        }
                    }
                    else
                    {
                        result = new ServiceResult <object> {
                            IsSucceed = false, StatusCode = (int)ServiceStatusCode.RequestError, Message = "Request error"
                        };
                        isSuccess = false;
                    }
                }
            }
            return(isSuccess);
        }
        /// <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);
        }
Esempio n. 7
0
        public async Task InvokeAsync(RemoteInvokeMessage message, int requestTimeout)
        {
            var          host    = NetUtils.GetHostAddress();
            AddressModel address = host;
            var          route   = await _serviceRotueProvider.GetRouteByPath(_routePath);

            if (route != null && route.Address.Count() > 1)
            {
                try
                {
                    var addresses = route.Address.ToList();
                    var index     = addresses.IndexOf(host);
                    for (var i = 1; i < AppConfig.Option.ClusterNode; i++)
                    {
                        ++index;
                        if (addresses.Count == index)
                        {
                            index = 0;
                        }
                        address = addresses[index];
                        if (host == address)
                        {
                            break;
                        }
                        var endPoint = address.CreateEndPoint();
                        if (_logger.IsEnabled(LogLevel.Debug))
                        {
                            _logger.LogDebug($"使用地址:'{endPoint}'进行调用。");
                        }
                        var client = await _transportClientFactory.CreateClientAsync(endPoint);

                        using (var cts = new CancellationTokenSource())
                        {
                            await client.SendAsync(message, cts.Token).WithCancellation(cts, requestTimeout);
                        }
                    }
                }
                catch (CommunicationException ex)
                {
                    await _healthCheckService.MarkFailure(address);
                }
                catch (Exception exception)
                {
                    _logger.LogError(exception, $"发起live请求中发生了错误,服务Id:{message.ServiceId}。");
                }
            }
        }
Esempio n. 8
0
        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 ?? ""));
        }
Esempio n. 9
0
        private bool OnAuthorization(string path, Dictionary <string, object> model, ref ServiceResult <object> result)
        {
            bool isSuccess = true;
            var  route     = _serviceRouteProvider.GetRouteByPath(path).Result;

            if (route.ServiceDescriptor.EnableAuthorization())
            {
                if (route.ServiceDescriptor.AuthType() == AuthorizationType.JWT.ToString())
                {
                    isSuccess = ValidateJwtAuthentication(route, model, ref result);
                }
                else
                {
                    isSuccess = ValidateAppSecretAuthentication(route, path, model, ref result);
                }
            }
            return(isSuccess);
        }
Esempio n. 10
0
        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);
        }
Esempio n. 11
0
        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);
        }