简体   繁体   中英

Why is my ServicePointManager.ServerCertificateValidationCallback being ignored?

I'm making a web request in a winforms app. I'm providing custom certificate validation like so:

    ServicePointManager.ServerCertificateValidationCallback += 
        new RemoteCertificateValidationCallback(certValidator.ValidateRemoteCertificate);

where certValidator.ValidateRemoteCertificate is

public bool ValidateRemoteCertificate(object sender, X509Certificate certificate,
                                      X509Chain chain, SslPolicyErrors policyErrors)
{
        return false;
}

As you can see, this callback should reject all server certificates and close any attempted connections.

My problem is that this callback is completely ignored. I submit an https request and it works like a charm. Watching it in the debugger I can see that ValidateRemoteCertificate is never invoked.

Why is my replacement callback never called back?

EDIT: LB asked for the webrequest, so here it is:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sourceUrl);
request.UseDefaultCredentials = true;
request.UserAgent = "Mozilla/5.0 (Windows; U; MSIE 9.0; WIndows NT 9.0; en-US))";    

request.KeepAlive = false;
request.Headers.Add("Accept-Language", "en-us,en;q=1.0");
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

EDIT 2: It's probably unrelated, but in the .config file I instruct it to use the configured proxy like so:

<system.net>
    <defaultProxy useDefaultCredentials="true"/>
</system.net>

EDIT 3: Below is a complete, minimal example that manifests the behavior. I expect this example to throw an exception because all certificates should be rejected, but it works just fine.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;

namespace SPMCertCallbackDemonstrator
{
    class Program
    {
        static void Main(string[] args)
        {
            ServicePointManager.ServerCertificateValidationCallback = delegate { return false;};
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.google.com");
            request.Method = "GET";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        }
    }
}

Why is my replacement callback never called back?

There was nothing wrong with the original code I posted. I was requesting over http instead of https. Thus no certificate validation was required. As soon as I invoked an https request, it worked fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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