Exemplo n.º 1
0
        public async Task <string> GetFromKeyVault(string posurl, bool ignore404 = false)
        {
            if (
                !string.IsNullOrEmpty(posurl) &&
                posurl.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase) &&
                posurl.Contains(".vault.azure.net/", StringComparison.InvariantCultureIgnoreCase) &&
                this.AccessTokenFetcher != null &&
                this.HttpClient != null
                )
            {
                // get an access token
                var accessToken = await AccessTokenFetcher.GetAccessToken("https://vault.azure.net", "VAULT");

                // get from the keyvault
                using (var request = new HttpRequestMessage()
                {
                    RequestUri = new Uri($"{posurl}?api-version=7.0"),
                    Method = HttpMethod.Get
                })
                {
                    request.Headers.Add("Authorization", $"Bearer {accessToken}");
                    using (var response = await this.HttpClient.SendAsync(request))
                    {
                        var raw = await response.Content.ReadAsStringAsync();

                        if (ignore404 && (int)response.StatusCode == 404) // Not Found
                        {
                            return(string.Empty);
                        }
                        else if (!response.IsSuccessStatusCode)
                        {
                            throw new Exception($"Config.GetFromKeyVault: HTTP {(int)response.StatusCode} - {raw}");
                        }
                        var item = JsonConvert.DeserializeObject <KeyVaultItem>(raw);
                        return(item.value);
                    }
                };
            }
            else
            {
                return(posurl);
            }
        }
Exemplo n.º 2
0
        public async Task <Dictionary <string, string> > Load(string[] filters, bool useFullyQualifiedName = false)
        {
            // exit if there is nothing requested or no way to get it
            Dictionary <string, string> kv = new Dictionary <string, string>();

            if (string.IsNullOrEmpty(AppConfig))
            {
                return(kv);
            }
            if (filters == null || filters.Length < 1)
            {
                return(kv);
            }
            if (this.AccessTokenFetcher == null || this.HttpClient == null)
            {
                return(kv);
            }

            // get an accessToken
            string accessToken = await AccessTokenFetcher.GetAccessToken($"https://{AppConfig}", "CONFIG");

            // process each key filter request
            foreach (var filter in filters)
            {
                // make authenticated calls to Azure AppConfig
                using (var request = new HttpRequestMessage()
                {
                    RequestUri = new Uri($"https://{AppConfig}/kv?key={filter}"),
                    Method = HttpMethod.Get
                })
                {
                    request.Headers.Add("Authorization", $"Bearer {accessToken}");
                    using (var response = await this.HttpClient.SendAsync(request))
                    {
                        // evaluate the response
                        var raw = await response.Content.ReadAsStringAsync();

                        if ((int)response.StatusCode == 401 || (int)response.StatusCode == 403)
                        {
                            throw new Exception($"Load: The identity is not authorized to get key/value pairs from the AppConfig \"{AppConfig}\"; make sure this is the right instance and that you have granted rights to the Managed Identity or Service Principal. If running locally, make sure you have run an \"az login\" with the correct account and subscription.");
                        }
                        else if (!response.IsSuccessStatusCode)
                        {
                            throw new Exception($"Load: HTTP {(int)response.StatusCode} - {raw}");
                        }

                        // look for key/value pairs
                        var json = JsonConvert.DeserializeObject <AppConfigItems>(raw);
                        foreach (var item in json.items)
                        {
                            Logger.LogDebug($"Config.Load: loaded \"{item.key}\" = \"{item.value}\".");
                            var key = (useFullyQualifiedName) ? item.key : item.key.Split(":").Last();
                            key = key.ToUpper();
                            var val = item.value;
                            if (item.content_type != null && item.content_type.Contains("vnd.microsoft.appconfig.keyvaultref", StringComparison.InvariantCultureIgnoreCase))
                            {
                                val = JsonConvert.DeserializeObject <KeyVaultRef>(item.value).uri;
                            }
                            if (!kv.ContainsKey(key))
                            {
                                kv.Add(key, val);
                            }
                        }
                    };
                }
            }

            return(kv);
        }