Ejemplo n.º 1
0
        private async Task <JObject> GetAllRoutes()
        {
            const string routeCacheKey = "GatewayRouteCache";
            var          routes        = _inMemoryCacheService.Get <JObject>(routeCacheKey);

            if (routes == null)
            {
                if (!string.IsNullOrEmpty(ApplicationConfig.ApiGatewayEndpoint))
                {
                    routes = await CallAsync(CommonConst.ActionMethods.GET, "/gateway/routes", "", null, null, ApplicationConfig.ApiGatewayEndpoint);

                    _inMemoryCacheService.Put <JObject>(routeCacheKey, routes);
                }
            }

            return(routes);
        }
Ejemplo n.º 2
0
 private List <T> GetDBValueAddToCache <T>(string tablename, List <T> input = null, JObject filter = null) where T : class
 {
     lock (lockobject)
     {
         if (input == null)
         {
             input = new List <T>();
         }
         if (filter == null)
         {
             filter = new JObject();
         }
         var r = _rdBService.Get <T>(tablename, DefaultGetpageLength, 0, filter);
         if (r != null && r.Any())
         {
             input.AddRange(r.ToList());
         }
         if (input.Any())
         {
             _inMemoryCacheService.Put <List <T> >($"{cacheprefix}-{tablename}-{filter.ToString()}", input);
         }
         return(input);
     }
 }
Ejemplo n.º 3
0
        public virtual bool AuthorizedRoute(HttpContext context, RoutingModel route, IAuthorizationService authorizationService)
        {
            var ssourl = CommonUtility.GetAppConfigValue(CommonConst.CommonValue.SSOURL_CONFIG_KEY);

            if (!route.auth_users.Where(f => f == CommonConst.CommonValue.ACCESS_ALL).Any() && !string.IsNullOrEmpty(ssourl))
            {
                try
                {
                    if (route.auth_users.IndexOf(CommonConst.CommonField.API_AUTH_TOKEN) != -1)
                    {
                        var api_access_key = _httpContextProxy.GetHeader(CommonConst.CommonField.API_AUTH_TOKEN);
                        return(api_access_key == CommonUtility.GetApiAuthKey());
                    }

                    var oauthclient = context.Request.Headers[CommonConst.CommonField.OAUTH_CLIENT_ID];
                    if (!string.IsNullOrEmpty(oauthclient))
                    {
                        var oauthUser = ValidateOAuthRequest(oauthclient, context, route);
                        return(oauthUser != null);
                    }

                    UserModel userModel = null;
                    userModel = _httpContextProxy.User;

                    if (userModel == null) // || (userModel != null && userModel.user_id == "auth2")
                    {
                        var accessToken = _httpContextProxy.GetAccessTokenAync().GetAwaiter().GetResult();
                        var cackeKey    = $"{accessToken}";
                        userModel = _inMemoryCacheService.Get <UserModel>(cackeKey);
                        if (userModel == null)
                        {
                            var endpoint = ApplicationConfig.AppEndpoint;
                            if (endpoint == ApplicationConfig.SSOEndpoint)
                            {
                                endpoint = ApplicationConfig.ApiGatewayEndpoint;
                            }
                            var response = _apiGatewayService.CallAsync(CommonConst.ActionMethods.GET, "~/user/getuserinfo", "", null, new Dictionary <string, string>()
                            {
                            }, endpoint).GetAwaiter().GetResult();
                            if (response["user"] != null)
                            {
                                userModel = JsonConvert.DeserializeObject <UserModel>(response["user"].ToString());
                                _inMemoryCacheService.Put <UserModel>(cackeKey, userModel);
                            }
                        }
                        if (userModel != null)
                        {
                            var identity = new ClaimsIdentity();
                            foreach (var claim in userModel.claims)
                            {
                                if (claim.Key == "roles")
                                {
                                    var roles = new List <string>();
                                    roles.AddRange(userModel.roles);
                                    identity.AddClaim(new System.Security.Claims.Claim("roles", Newtonsoft.Json.JsonConvert.SerializeObject(roles)));
                                }
                                else
                                {
                                    identity.AddClaim(new System.Security.Claims.Claim(claim.Key, claim.Value));
                                }
                            }
                            context.User = new ClaimsPrincipal(identity);
                        }
                    }

                    if (userModel != null)
                    {
                        if (userModel.tenants != null && userModel.tenants.Any())
                        {
                            context.Response.Headers[CommonConst.CommonField.TENANT_ID] = userModel.tenants.First().tenant_id;
                        }

                        var u = _httpContextProxy.User;
                        _logger.Debug($"Assign user id :{u.user_id} Claims:{string.Join(", ", u.claims.Select(f => $"{f.Key}:{f.Value}"))} OrgRoles: { string.Join(",", userModel.roles)}");

                        var hasaccess = false;

                        hasaccess = userModel.roles.Where(f => route.auth_users.IndexOf(f) != -1).Any();
                        if (!hasaccess)
                        {
                            _logger.Debug($"Access :{hasaccess}:{route.ToString()}:{  string.Join(",", route.auth_users)}");
                        }
                        return(hasaccess);
                    }
                    return(false);
                }
                catch (UnauthorizedAccessException)
                {
                    return(false);
                }
            }
            else
            {
                return(true);
            }
        }
Ejemplo n.º 4
0
        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);
        }