使用ServerCertificateValidationCallback的最佳做法 [英] Best practices for using ServerCertificateValidationCallback

查看:544
本文介绍了使用ServerCertificateValidationCallback的最佳做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个项目中,该项目在两个后端服务器之间使用一些HTTP通信。服务器正在使用X509证书进行身份验证。不用说,当服务器A(客户端)建立与服务器B(服务器)的连接时,会出现SSL / TLS验证错误,因为所使用的证书不是来自受信任的第三方授权。

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中是否存在更好的做法,该做法允许在处理客户端SSL /的同时访问Web服务。 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的最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆