c# - 通过代理使用 KeyVaultClient

标签 c# azure asp.net-core azure-keyvault

目前,我在启动期间使用 Azure KeyVault 来加载一些配置,如下所示:

configBuilder
    .AddAzureKeyVault(keyVaultConfigSection.Vault, GetKeyVaultClient(clientConfigSection, keyVaultConfigSection), new DefaultKeyVaultSecretManager())
    .AddEnvironmentVariables();

private static KeyVaultClient GetKeyVaultClient(ClientConfigSection clientConfigSection, KeyVaultConfigSection keyVaultConfigSection)
{
    HttpClient httpClient = null;

    //proxy
    if (!CustomEnvironment.NotProductionEnvironment())
    {
        var handler = new HttpClientHandler()
        {
            Proxy = new WebProxy(keyVaultConfigSection.Proxy),
            UseProxy = true
        };
        httpClient = new HttpClient(handler);
    }

    return new KeyVaultClient(async (authority, resource, scope) =>
        {
            var authContext = new AuthenticationContext(authority);
            var clientCred = new ClientCredential(clientConfigSection.ClientId, clientConfigSection.ClientSecret);
            var result = await authContext.AcquireTokenAsync(resource, clientCred);
            if (result == null)
                throw new InvalidOperationException("Failed to retrieve access token for Key Vault");
            return result.AccessToken;
        }, httpClient ?? new HttpClient()
    );
}

当我不在生产环境中时,这工作得很好。 但在我们的生产环境中,keyvault 被阻止,因此我们必须通过代理。

但是在运行代码时,我收到此错误:Microsoft.Azure.KeyVault.Models.KeyVaultErrorException:'操作返回无效的状态代码'BadRequest''

以前有人这样做过并且可以为我指明正确的方向吗?

最佳答案

好像还没修复,这里是workaround .

1.引用System.Net.Http.WinHttpHandler Nuget包来访问.NET Core中的WinHttpHandler。

2.创建了一个新的MyKeyVaultCredential,它继承自KeyVaultCredential并重写ProcessHttpRequestAsync方法

public override async Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
 {
     if (request == null)
     {
         throw new ArgumentNullException("request");
     }

     var accessToken = await PreAuthenticate(request.RequestUri).ConfigureAwait(false);
     if (!string.IsNullOrEmpty(accessToken))
         request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
     else
     {
         var httpClientHandler = new WinHttpHandler()
         {
             WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseCustomProxy,
             Proxy = new MyWebProxy(configuration),
             SendTimeout = TimeSpan.FromSeconds(120),
             ReceiveDataTimeout = TimeSpan.FromSeconds(120),
             ReceiveHeadersTimeout = TimeSpan.FromSeconds(120),
         };

3.当我实例化 KeyVaultService 时,我必须向 WinHttpHandler 提供我的代理和新的 key 保管库凭据实例。

var httpClientHandler = new WinHttpHandler()
     {
         WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseCustomProxy,
         Proxy = new MyWebProxy(configuration),
         SendTimeout = TimeSpan.FromSeconds(120),
         ReceiveDataTimeout = TimeSpan.FromSeconds(120),
         ReceiveHeadersTimeout= TimeSpan.FromSeconds(120),
     };

     var httpClient = new HttpClient(httpClientHandler);

     client = new KeyVaultClient(new  MyKeyVaultCredential(configuration, GetToken), httpClient)

希望这有帮助。

关于c# - 通过代理使用 KeyVaultClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57590393/

相关文章:

azure - 如何在 Azure 函数中处理 IoTHub 文件上传通知

c# - 预加载多对多 - EF Core

c# - 在 .NET Core API 应用程序中使用 FluentScheduler 期间的 DependencyInjection 问题

c# - .NET Entity Framework 项目布局(架构)

c# - 双重数据认可?

c# - 对使用 Azure 云服务的代码进行单元测试

azure - 为什么无法将数据存储在 Azure 计算实例中?

c# - 如何以重构安全的方式使用 JSON.Net 来获取持久数据

c# - EF 4.1 代码优先 : Each property name in a type must be unique error on Lookup Table association

c# - 在 ASP.NET 5 中使用通用 OAuth 中间件时出现 401 未经授权