我有一个 C# ASP.NET 项目,它使用两个库 Azure.Security.KeyVault.Secrets 和 Azure.Identity 从 Azure Key Vault 检索某些机密。如何使 GetSecretAsync 请求通过代理?我需要专门为这些调用设置一个代理。有推荐的方法来实现这一目标吗?
using System;
using System.Configuration;
using System.Net;
using System.Net.Http;
using Azure.Core.Pipeline;
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
namespace Helpers
{
public class KeyVaultHelper
{
public static Settings Get()
{
try
{
string keyVaultUrl = ConfigurationManager.AppSettings["url"];
string proxyAddress = "http://myproxy.bankfab.com:8080";
var appId = ConfigurationManager.AppSettings["APP_ID"];
var appKey = ConfigurationManager.AppSettings["APP_KEY"];
var tenantId = ConfigurationManager.AppSettings["TENANT_ID"];
var credential = new ClientSecretCredential(tenantId, appId, appKey);
var secretClient = new SecretClient(new Uri(keyVaultUrl), credential);
var publicKey = secretClient.GetSecretAsync(ConfigurationManager.AppSettings["secret1"]).GetAwaiter().GetResult().Value;
var secretKey = secretClient.GetSecretAsync(ConfigurationManager.AppSettings["secret2"]).GetAwaiter().GetResult().Value;
var clientId = secretClient.GetSecretAsync(ConfigurationManager.AppSettings["secret3"]).GetAwaiter().GetResult().Value;
var clientSecret = secretClient.GetSecretAsync(ConfigurationManager.AppSettings["secret4"]).GetAwaiter().GetResult().Value;
return new Settings
{
Secret1 = publicKey.Value,
Secret2 = secretKey.Value,
Secret3 = clientId.Value,
Secret4 = clientSecret.Value
};
}
catch (Exception ex)
{
throw;
}
}
}
}
我尝试使用代理创建一个新的http,并尝试使用它,但我不知道它是否正确。
string proxyAddress = "http://your-proxy-address";
var proxy = new WebProxy(proxyAddress);
var httpClientHandler = new HttpClientHandler
{
Proxy = proxy,
UseProxy = true,
};
using (var httpClient = new HttpClient(httpClientHandler))
{
var secretClientOptions = new SecretClientOptions
{
Transport = new HttpClientTransport(httpClient)
};
var secretClient = new SecretClient(new Uri(keyVaultUrl), credential, secretClientOptions);
//my logic with GetSecretAsync
}
您尝试的方式是正确的,我尝试过,并且可以通过以下代码使用代理获取 Azure 密钥保管库机密
// 程序.cs
使用Azure.Identity; 使用 Azure.Security.KeyVault.Secrets; 使用 System.Net.Http; 使用System.Net; 使用系统; 使用 Microsoft.Extensions.Configuration; 使用 Microsoft.Extensions.Options;
课程计划{ 私有只读 IConfiguration _configuration; 静态无效主(字符串[]参数) {
// Configure a named HttpClient with proxy settings using (var httpClient = new HttpClient(new HttpClientHandler { Proxy = new WebProxy("http://xxx.xxx.x.xxx:139"), UseProxy = true, })) { // Create a new instance of the SecretClient class SecretClient mysecretvalue = new SecretClient(new Uri("https://proxy3.vault.azure.net/"), new DefaultAzureCredential()); // Use the SecretClient to retrieve secrets KeyVaultSecret secret = mysecretvalue.GetSecret("PublicKeySecretName"); // Now you can use the retrieved secret Console.WriteLine($"Secret: {secret.Value}"); } Console.WriteLine("Press Enter to exit..."); Console.ReadLine(); } }
秘密保存在门户中
在控制台和调试中获取值