Exemple #1
0
        public virtual async Task Invoke(HttpContext context, IAuthorizationService authorizationService)
        {
            var route = _routing.GetRoute(_httpContextProxy.GetHttpMethod(), _httpContextProxy.GetURIAbsolutePath());

            if (route != null && !string.IsNullOrEmpty(route.ExecultAssembly) && !string.IsNullOrEmpty(route.ExecuteType))
            {
                if (AuthorizedRoute(context, route, authorizationService))
                {
                    var type = _assemblyLoader.GetType(route.ExecultAssembly, route.ExecuteType);
                    if (type != null)
                    {
                        context.Response.Headers[CommonConst.CommonField.MODULE_NAME]  = route.module_name;
                        context.Response.Headers[CommonConst.CommonField.EXECUTE_TYPE] = route.ExecuteType;
                        context.Response.Headers[CommonConst.CommonField.ROUTE]        = $"{route.Method}:{route.Route}";

                        _logger.Debug(string.Format("Executing route:{0}", route.ToString()));
                        var controller = _serviceResolver.Resolve(type);
                        var method     = controller.GetType().GetMethods().FirstOrDefault(f => f.Name == route.ExecuteMethod);
                        if (method != null)
                        {
                            context.Response.ContentType = route.ContentType;
                            object response = null;
                            if (method.ReturnType.BaseType == typeof(Task))
                            {
                                response = await(dynamic) method.Invoke(controller, null);
                            }
                            else
                            {
                                response = method.Invoke(controller, null);
                            }
                            RemoveHeaders(context);
                            if (response != null)
                            {
                                if (method.ReturnType == typeof(string))
                                {
                                    await context.Response.WriteAsync((response as string));
                                }
                                else if (method.ReturnType == typeof(byte[]))
                                {
                                    var byteResponse = response as byte[];
                                    await context.Response.Body.WriteAsync(byteResponse, 0, byteResponse.Length);
                                }
                                else
                                {
                                    await context.Response.WriteAsync(JsonConvert.SerializeObject(response));
                                }
                            }
                            else
                            {
                                await context.Response.Body.WriteAsync(new byte[] { });
                            }
                        }
                        else
                        {
                            RemoveHeaders(context);
                            _logger.Error($"Method not found for route : {route.ToString()}");
                            context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                            await context.Response.WriteAsync(_responseBuilder.NotFound().ToString());
                        }
                    }
                    else
                    {
                        _logger.Error($"Type not found for route : {route.ToString()}");
                        context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                        await context.Response.WriteAsync(_responseBuilder.NotFound().ToString());
                    }
                }
                else
                {
                    context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                    await context.Response.WriteAsync(_responseBuilder.Unauthorized().ToString());
                }
            }
            else
            {
                try
                {
                    route = await _apiGatewayService.GetRouteAsync(_httpContextProxy.GetHttpMethod(), _httpContextProxy.GetURIAbsolutePath());

                    if (route != null)
                    {
                        try
                        {
                            context.Response.ContentType = route.ContentType;
                            JObject response = await CallRemoteRouteCalls(context, route);

                            if (response != null)
                            {
                                RemoveHeaders(context);
                                if (response["content_type"] != null && response["data"] != null)
                                {
                                    await context.Response.WriteAsync(response["data"].ToString());
                                }
                                else
                                {
                                    await context.Response.WriteAsync(response.ToString());
                                }
                            }
                            else
                            {
                                await _next(context);
                            }
                        }
                        catch (UnauthorizedAccessException ex)
                        {
                            context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                            _logger.Error($"UnauthorizedAccessException remote route. {route.ToString() } . {ex.Message}", ex);
                        }
                        catch (Exception ex)
                        {
                            _logger.Error($"Error Executing remote route. {route.ToString() } . {ex.Message}", ex);
                            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                        }
                    }
                    else
                    {
                        await _next(context);
                    }
                }

                catch (Exception ex)
                {
                    _logger.Error($"Error Executing remote route. {route.ToString() } . {ex.Message}", ex);
                    await _next(context);
                }
            }
        }
        public OAuthClient FetchClient(string clientId)
        {
            var route = _apiGatewayService.GetRouteAsync(CommonConst.ActionMethods.GET, oauthClientApiPath).GetAwaiter().GetResult();

            if (route != null)
            {
                var result = _apiGatewayService.CallAsync(CommonConst.ActionMethods.GET, oauthClientApiPath, $"client_id={clientId}").GetAwaiter().GetResult();
                if (result[CommonConst.CommonField.HTTP_RESPONE_CODE].ToString() == CommonConst._1_SUCCESS.ToString())
                {
                    var clientname = result["data"]["client_id"].ToString();
                    if (result["data"]["name"] != null)
                    {
                        clientname = result["data"]["name"].ToString();
                    }
                    var tenantId = string.Empty;
                    if (result["data"]["tenant_id"] != null)
                    {
                        tenantId = result["data"]["tenant_id"].ToString();
                    }
                    var roles = new List <string>();

                    if (result["data"]["roles"] != null)
                    {
                        roles.AddRange((result["data"]["roles"] as JArray).Select(f => f.ToString()));
                    }

                    var salt = string.Empty;
                    if (result["data"]["salt"] != null)
                    {
                        salt = result["data"]["salt"].ToString();
                    }

                    var encKey = string.Empty;
                    if (result["data"]["encryption_key"] != null)
                    {
                        encKey = result["data"]["encryption_key"].ToString();
                    }
                    var ips = new List <string>();

                    if (result["data"]["ips"] != null)
                    {
                        foreach (var ip in result["data"]["ips"] as JArray)
                        {
                            ips.Add(ip["ip"].ToString());
                        }
                    }
                    var client = new OAuthClient
                    {
                        Client = new Client()
                        {
                            AllowedGrantTypes  = GrantTypes.ClientCredentials,
                            ClientName         = clientname,
                            ClientId           = result["data"]["client_id"].ToString(),
                            ClientSecrets      = { new Secret(result["data"]["client_secret"].ToString()) },
                            AllowOfflineAccess = true,
                        },
                        Secret        = result["data"]["client_secret"].ToString(),
                        TenantId      = tenantId,
                        Roles         = roles,
                        Salt          = salt,
                        EncryptionKey = encKey,
                        IPs           = ips
                    };
                    var allowedScopes = new List <string>()
                    {
                        "openid", "profile", "ZNxtCoreAppApi"
                    };
                    if (result["data"]["allowed_scopes"] != null)
                    {
                        allowedScopes.AddRange((result["data"]["allowed_scopes"] as JArray).Select(f => f.ToString()).ToList());
                    }

                    client.Client.AllowedScopes = allowedScopes;
                    _inMemoryCacheService.Put <OAuthClient>($"{cachePrefix}{clientId}", client);
                    return(client);
                }
            }
            return(null);
        }