147

我正在尝试找到一种在请求 Https 资源时忽略证书检查的方法,到目前为止,我在互联网上找到了一些有用的文章。

但我还是有一些问题。请查看我的代码。我只是不明白代码是什么ServicePointManager.ServerCertificateValidationCallback意思。

什么时候调用这个委托方法?还有一个问题,我应该在哪个地方写这段代码?在ServicePointManager.ServerCertificateValidationCallback执行之前还是之前Stream stream = request.GetRequestStream()

public HttpWebRequest GetRequest()
{
    CookieContainer cookieContainer = new CookieContainer();

    // Create a request to the server
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_remoteUrl);

    #region Set request parameters

    request.Method = _context.Request.HttpMethod;
    request.UserAgent = _context.Request.UserAgent;
    request.KeepAlive = true;
    request.CookieContainer = cookieContainer;
    request.PreAuthenticate = true;
    request.AllowAutoRedirect = false;

    #endregion

    // For POST, write the post data extracted from the incoming request
    if (request.Method == "POST")
    {
        Stream clientStream = _context.Request.InputStream;
        request.ContentType = _context.Request.ContentType;
        request.ContentLength = clientStream.Length;

        ServicePointManager.ServerCertificateValidationCallback = delegate(
            Object obj, X509Certificate certificate, X509Chain chain, 
            SslPolicyErrors errors)
            {
                return (true);
            };

            Stream stream = request.GetRequestStream();

            ....
        }

        ....

        return request;
    }
}   
4

16 回答 16

192

对于有兴趣在每个请求的基础上应用此解决方案的任何人,这是一个选项并使用 Lambda 表达式。同样的 Lambda 表达式也可以应用于 blak3r 提到的全局过滤器。此方法似乎需要 .NET 4.5。

String url = "https://www.stackoverflow.com";
HttpWebRequest request = HttpWebRequest.CreateHttp(url);
request.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;

在 .NET 4.0 中,Lambda 表达式可以这样应用于全局过滤器

ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
于 2013-09-04T21:47:10.433 回答
72

由于只有一个全局ServicePointManager,因此设置ServicePointManager.ServerCertificateValidationCallback将产生所有后续请求都将继承此策略的结果。由于它是一个全局“设置”,因此最好在Global.asax的Application_Start方法中进行设置。

设置回调会覆盖默认行为,您可以自己创建自定义验证例程。

于 2012-09-20T06:26:31.797 回答
58

这对我有用:

System.Net.ServicePointManager.ServerCertificateValidationCallback +=
delegate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate,
                        System.Security.Cryptography.X509Certificates.X509Chain chain,
                        System.Net.Security.SslPolicyErrors sslPolicyErrors)
    {
        return true; // **** Always accept
    };

来自这里的片段:http ://www.west-wind.com/weblog/posts/2011/Feb/11/HttpWebRequest-and-Ignoring-SSL-Certificate-Errors

于 2013-04-29T22:38:35.443 回答
29

还有短委托解决方案:

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; 
于 2015-08-13T12:57:27.810 回答
10

顺便说一句,这是我所知道的在给定应用程序中关闭所有证书验证的最简单的方法:

ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => true;
于 2016-02-04T23:29:46.323 回答
7

您可以在 HttpClient 的本地实例上设置回调,而不是向 ServicePointManager 添加一个将全局覆盖证书验证的回调。这种方法应该只影响使用该 HttpClient 实例进行的调用。

下面的示例代码展示了如何在 Web API 控制器中实现忽略特定服务器的证书验证错误。

using System.Net.Http;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

public class MyController : ApiController
{

    // use this HttpClient instance when making calls that need cert errors suppressed
    private static readonly HttpClient httpClient;

    static MyController()
    {
        // create a separate handler for use in this controller
        var handler = new HttpClientHandler();

        // add a custom certificate validation callback to the handler
        handler.ServerCertificateCustomValidationCallback = ((sender, cert, chain, errors) => ValidateCert(sender, cert, chain, errors));

        // create an HttpClient that will use the handler
        httpClient = new HttpClient(handler);
    }

    protected static ValidateCert(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors)
    {

        // set a list of servers for which cert validation errors will be ignored
        var overrideCerts = new string[]
        {
            "myproblemserver",
            "someotherserver",
            "localhost"
        };

        // if the server is in the override list, then ignore any validation errors
        var serverName = cert.Subject.ToLower();
        if (overrideCerts.Any(overrideName => serverName.Contains(overrideName))) return true;

        // otherwise use the standard validation results
        return errors == SslPolicyErrors.None;
    }

}
于 2018-12-18T16:46:57.157 回答
6

对于 .net 核心

using (var handler = new HttpClientHandler())
{ 
    // allow the bad certificate
    handler.ServerCertificateCustomValidationCallback = (request, cert, chain, errors) => true;
    using (var httpClient = new HttpClient(handler))
    {
        await httpClient.PostAsync("the_url", null);
    }
}
于 2020-05-14T17:00:17.293 回答
5

已经提到,在 .NET 4.5 之前,请求访问其的属性ServicePointManager不可用。

这是 .NET 4.0 代码,可让您ServicePoint按请求访问。它不会让您访问每个请求的回调,但它应该让您找到有关问题的更多详细信息。只需访问scvPoint.Certificate(或ClientCertificate如果您愿意)属性。

WebRequest request = WebRequest.Create(uri);

// oddity: these two .Address values are not necessarily the same!
//  The service point appears to be related to the .Host, not the Uri itself.
//  So, check the .Host vlaues before fussing in the debugger.
//
ServicePoint svcPoint = ServicePointManager.FindServicePoint(uri);
if (null != svcPoint)
{
    if (!request.RequestUri.Host.Equals(svcPoint.Address.Host, StringComparison.OrdinalIgnoreCase))
    {
        Debug.WriteLine(".Address              == " + request.RequestUri.ToString());
        Debug.WriteLine(".ServicePoint.Address == " + svcPoint.Address.ToString());
    }
    Debug.WriteLine(".IssuerName           == " + svcPoint.Certificate.GetIssuerName());
}
于 2014-03-06T17:43:37.517 回答
4

CA5386:漏洞分析工具会提醒您注意这些代码。

正确的代码:

ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) =>
{
   return (sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable) != SslPolicyErrors.RemoteCertificateNotAvailable;
};
于 2019-07-29T02:09:28.043 回答
3

根据亚当的回答和罗布的评论,我使用了这个:

ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => certificate.Issuer == "CN=localhost";

这在某种程度上过滤了“忽略”。当然可以根据需要添加其他发行人。这是在 .NET 2.0 中测试的,因为我们需要支持一些遗留代码。

于 2014-05-08T07:12:03.357 回答
2

明确表达...

ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(CertCheck);

private static bool CertCheck(object sender, X509Certificate cert,
X509Chain chain, System.Net.Security.SslPolicyErrors error)
{
    return true;
}
于 2019-04-15T01:09:17.903 回答
2

此解决方案的 Unity C# 版本:

void Awake()
{
    System.Net.ServicePointManager.ServerCertificateValidationCallback += ValidateCertification;
}

void OnDestroy()
{
    ServerCertificateValidationCallback = null;
}

public static bool ValidateCertification(object sender, X509Certificate certificate, X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
    return true;
}
于 2020-03-03T12:13:45.007 回答
1

在 .NetCore 3.1 上,您可以通过声明自定义验证方法来解决此问题。

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };  
  

所以在发出请求之前,声明这个回调方法

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };    
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://someurl.com/service/");  
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();  
  

这样,验证将始终通过,因为您的自定义方法始终返回true值。

于 2021-05-13T15:18:36.083 回答
0

添加到 Sani 和 blak3r 的答案中,我在我的应用程序的启动代码中添加了以下内容,但在 VB 中:

'** Overriding the certificate validation check.
Net.ServicePointManager.ServerCertificateValidationCallback = Function(sender, certificate, chain, sslPolicyErrors) True

似乎可以解决问题。

于 2013-07-05T22:15:35.693 回答
0

以上工作的几个答案。我想要一种方法,我不必不断地更改代码并且不会使我的代码不安全。因此,我创建了一个白名单。白名单可以在任何数据存储中维护。我使用了配置文件,因为它是一个非常小的列表。

我的代码如下。

ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, error) => {
    return error == System.Net.Security.SslPolicyErrors.None || certificateWhitelist.Contains(cert.GetCertHashString());
};
于 2018-10-15T19:57:14.207 回答
0

提示:您也可以使用此方法来跟踪即将到期的证书。如果您发现即将过期的证书并且可以及时修复它,这可以节省您的培根。对第三方公司也有好处 - 对我们来说,这是 DHL / FedEx。DHL 只是让证书过期,这让我们在感恩节前 3 天搞砸了。幸运的是,我正在修复它......这次!

    private static DateTime? _nextCertWarning;
    private static bool ValidateRemoteCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error)
    {
        if (error == SslPolicyErrors.None)
        {
            var cert2 = cert as X509Certificate2;
            if (cert2 != null)
            { 
                // If cert expires within 2 days send an alert every 2 hours
                if (cert2.NotAfter.AddDays(-2) < DateTime.Now)
                {
                    if (_nextCertWarning == null || _nextCertWarning < DateTime.Now)
                    {
                        _nextCertWarning = DateTime.Now.AddHours(2);

                        ProwlUtil.StepReached("CERT EXPIRING WITHIN 2 DAYS " + cert, cert.GetCertHashString());   // this is my own function
                    }
                }
            }

            return true;
        }
        else
        {
            switch (cert.GetCertHashString())
            {
                // Machine certs - SELF SIGNED
                case "066CF9CAD814DE2097D367F22D3A7E398B87C4D6":    

                    return true;

                default:
                    ProwlUtil.StepReached("UNTRUSTED CERT " + cert, cert.GetCertHashString());
                    return false;
            }
        }
    }
于 2017-11-21T19:18:01.520 回答