简体   繁体   English

我应该如何在 HttpClient 中使用证书?

[英]How should I use a certificate with HttpClient?

I need to use a web API from one of our partners.我需要使用我们的一位合作伙伴提供的 web API。 Their API require that I use a certificate to connect.他们的 API 要求我使用证书进行连接。

I do not want to install the certificate on our servers (VMs).我不想在我们的服务器 (VM) 上安装证书。 That is counterproductive to our phoenix server strategy.这对我们的凤凰服务器策略适得其反。

I try to use the certificate programmatically.我尝试以编程方式使用证书。 The problem is that I get an error:问题是我得到一个错误:

AuthenticationException: The remote certificate is invalid according to the validation procedure. AuthenticationException:根据验证程序,远程证书无效。

I create my HttpClient using this code:我使用以下代码创建我的HttpClient

_certificate = new X509Certificate2(_certificateFile);
var handler = new WebRequestHandler();
handler.ClientCertificates.Add(_certificate);
var client = new HttpClient(handler) { BaseAddress = new Uri(_url) };

I can make it work by overriding certificate validations:我可以通过覆盖证书验证使其工作:

ServicePointManager.ServerCertificateValidationCallback += delegate { return true; };

But that looks like poor style.但这看起来像糟糕的风格。

I have verified that my endpoint matches CN in the certificate我已验证我的端点与证书中的 CN 匹配

Is the AuthenticationException simply because certificate is not installed in the certificate store? AuthenticationException仅仅是因为证书未安装在证书存储中吗?

If yes, can I temporarily with code install the certificate and remove it after?如果是,我可以暂时使用代码安装证书并在之后将其删除吗?

"The remote certificate is invalid" indicates that .NET Framework thinks the server side certificate of your partner's web service is invalid (quite normal if you don't have necessary root/intermediate certificates installed). “远程证书无效”表示 .NET 框架认为您合作伙伴的 web 服务的服务器端证书无效(如果您没有安装必要的根/中间证书,则很正常)。

You can suppress the default check by changing ServerCertificateValidationCallback , but you should implement your own to make sure you do validate their certificate in a reasonable way to avoid attacks.您可以通过更改ServerCertificateValidationCallback来禁止默认检查,但您应该实现自己的以确保以合理的方式验证他们的证书以避免攻击。

You should also use HttpClientHandler.ServerCertificateValidationCallback , so that your custom validator only takes effect in the scope of this specific HttpClient instance, but does not affect elsewhere in your app,您还应该使用HttpClientHandler.ServerCertificateValidationCallback ,以便您的自定义验证器仅在此特定HttpClient实例的 scope 中生效,但不会影响您应用中的其他地方,

https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclienthandler.servercertificatecustomvalidationcallback?view=netframework-4.8 https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclienthandler.servercertificatecustomvalidationcallback?view=netframework-4.8

However, the certificate they gave you (usually a client certificate) is validated by their web service, not locally on your machine.但是,他们给您的证书(通常是客户端证书)由他们的 web 服务验证,而不是在您的计算机上本地验证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM