问题描述
我正在开发一个在两个后端服务器之间使用某些 HTTP 通信的项目.服务器使用 X509 证书进行身份验证.不用说,当服务器 A(客户端)与服务器 B(服务器)建立连接时,会出现 SSL/TLS 验证错误,因为使用的证书并非来自受信任的第 3 方机构.
I am working on a project that uses some HTTP communication between two back-end servers. Servers are using X509 certificates for authentication. Needless to say, when server A (client) establishes connection to server B (server), there is a SSL/TLS validation error, since certificates used are not from trusted 3rd party authority.
通常的处理方式是使用ServicePointManager.ServerCertificateValidationCallback
,如:
Normally, the way to handle it is using ServicePointManager.ServerCertificateValidationCallback
, such as:
ServicePointManager.ServerCertificateValidationCallback +=
(sender, cert, chain, error) =>
{
return cert.GetCertHashString() == "xxxxxxxxxxxxxxxx";
};
这种方法有效,但并不理想.它本质上所做的是覆盖应用程序完成的每个 http 请求的验证过程.因此,如果另一个类尝试运行 HTTP 请求,它将失败.此外,如果另一个类出于自己的目的覆盖了 ServicePointManager.ServerCertificateValidationCallback
,那么我的通信就会突然开始失败.
That approach works, except it's not ideal. What it essentially does is override validation procedure for EVERY http request done by the application. So, if another class will try to run HTTP request, it will fail. Also, if another class overrides ServicePointManager.ServerCertificateValidationCallback
for its own purposes, then my communication starts failing out of sudden.
想到的唯一解决方案是创建一个单独的 AppDomain 执行客户端 HTTP 请求.这会起作用,但实际上 - 只需要这样做是为了可以执行 HTTP 请求是愚蠢的.开销将是惊人的.
The only solution which comes to mind, is creating a separate AppDomain to perform client HTTP requests. That would work, but really - it's silly to have to do that only so that one can perform HTTP requests. Overhead will be staggering.
考虑到这一点,有没有人研究过 .NET 中是否有更好的做法,允许访问 Web 服务,同时处理客户端 SSL/TLS 验证而不影响其他 Web 客户端?
With that in mind, have anyone researched if there is a better practice in .NET, which would allow accessing web services, while handling client SSL/TLS validation without affecting other web clients?
推荐答案
在 .NET 4.5+ 中工作的一种可接受的(安全)方法是使用 HttpWebRequest.ServerCertificateValidationCallback
.在请求的特定实例上分配该回调将仅针对该请求更改验证逻辑,而不会影响其他请求.
An acceptable (safe) methodology working in .NET 4.5+ is to use HttpWebRequest.ServerCertificateValidationCallback
. Assigning that callback on a specific instance of request will change the validation logic just for the request, not influencing other requests.
var request = (HttpWebRequest)WebRequest.Create("https://...");
request.ServerCertificateValidationCallback +=
(sender, cert, chain, error) =>
{
return cert.GetCertHashString() == "xxxxxxxxxxxxxxxx";
};
这篇关于使用 ServerCertificateValidationCallback 的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!