【问题标题】:Disable SSL certificate verification in default injected IHttpClientFactory在默认注入的 IHttpClientFactory 中禁用 SSL 证书验证
【发布时间】:2020-07-12 11:07:46
【问题描述】:

在 Startup.cs 中,我注入了一个 IHttpClientFactory 服务:

services.AddHttpClient();

然后我可以通过

创建一个新的HttpClient
public MyClass(IHttpClientFactory httpClientFactory, IOptions<MyClassOptions> options)
{
    _httpClient = httpClientFactory.CreateClient();
    // ...
}

MyClass 做一些 API 访问;基本 URL 在 options 对象中传递。

为了测试,我设置了一个 API 的虚拟实例,它使用自签名 SSL 证书。不幸的是,这个证书被(正确地)识别为无效:

System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception.
 ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.

如何在工厂层禁用证书验证,即直接在ConfigureServices 方法中?

我找到了this question,但它似乎使用了一些自定义的HttpClient 实现(?),而我想定位默认的。以下不起作用(DI 选择了错误的构造函数并随后失败):

services.AddHttpClient<IMyClass, MyClass>();

This answer 建议为配置的HttpClient 提供一个名称,但它传递了一些我想避免的魔术字符串(MyClass 位于一个设计为也可供其他人使用的类库中)。不传递名称也不起作用,因为 AddHttpClient 然后只返回一个 IServiceCollection 对象。

【问题讨论】:

    标签: c# asp.net-core dependency-injection dotnet-httpclient


    【解决方案1】:

    我现在想通了。我们可以应用this answer来修改默认HttpClient的主HttpMessageHandler

    services.AddHttpClient(Options.DefaultName, c =>
    {
        // ...
    }).ConfigurePrimaryHttpMessageHandler(() =>
    {
        return new HttpClientHandler
        {
            ClientCertificateOptions = ClientCertificateOption.Manual,
            ServerCertificateCustomValidationCallback =
                (httpRequestMessage, cert, certChain, policyErrors) => true
        };
    });
    

    这将产生带有禁用 SSL 验证的 HttpClient 对象,只要注入默认的 IHttpClientFactory

    【讨论】:

      猜你喜欢
      • 2019-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-14
      • 2011-05-03
      • 2018-11-04
      • 1970-01-01
      相关资源
      最近更新 更多