How to ignore the certificate check when ssl

329,556

Solution 1

Since there is only one global ServicePointManager, setting ServicePointManager.ServerCertificateValidationCallback will yield the result that all subsequent requests will inherit this policy. Since it is a global "setting" it would be prefered to set it in the Application_Start method in Global.asax.

Setting the callback overrides the default behaviour and you can yourself create a custom validation routine.

Solution 2

For anyone interested in applying this solution on a per request basis, this is an option and uses a Lambda expression. The same Lambda expression can be applied to the global filter mentioned by blak3r as well. This method appears to require .NET 4.5.

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

In .NET 4.0, the Lambda Expression can be applied to the global filter as such

ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;

Solution 3

This worked for me:

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
    };

Snippet from here: http://www.west-wind.com/weblog/posts/2011/Feb/11/HttpWebRequest-and-Ignoring-SSL-Certificate-Errors

Solution 4

Also there is the short delegate solution:

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; 

Solution 5

Just incidentally, this is a the least verbose way of turning off all certificate validation in a given app that I know of:

ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => true;
Share:
329,556
Joe.wang
Author by

Joe.wang

An Asp.net developer. Sometimes in Java

Updated on May 14, 2021

Comments

  • Joe.wang
    Joe.wang about 3 years

    I am trying find a way to ignore the certificate check when request a Https resource, so far, I found some helpful article in internet.

    But I still have some problem. Please review my code. I just don't understand what does the code ServicePointManager.ServerCertificateValidationCallback mean.

    When will this delegate method be called? And one more question, in which place should I write this code? Before ServicePointManager.ServerCertificateValidationCallback execute or before 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;
        }
    }   
    
  • Andrej Grobler
    Andrej Grobler almost 10 years
    @karank Sorry for late reply - It can be added anywhere before the actual call, eg. before calling request.GetResponse(). Note that Issuer might contain something else in your case though.
  • David Rutgos
    David Rutgos almost 10 years
    ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
  • B. Clay Shannon-B. Crow Raven
    B. Clay Shannon-B. Crow Raven over 9 years
    What about for a client that has no Global.asax? I am calling a REST service running on the local network from a handheld device.
  • Sani Singh Huttunen
    Sani Singh Huttunen over 9 years
    The question is specific to HttpWebRequest. If you're using any other means you'll have to look in the documentation how to accomplish this.
  • B. Clay Shannon-B. Crow Raven
    B. Clay Shannon-B. Crow Raven over 9 years
    I'm using WebRequest, which gets cast to HttpWebRequest, such as: ((HttpWebRequest)request).Accept = contentType;
  • Sani Singh Huttunen
    Sani Singh Huttunen over 9 years
    As stated in my answer: it is PREFERRED to set it in Global.asax not a requirement. You can even set it before the call to the REST service.
  • B. Clay Shannon-B. Crow Raven
    B. Clay Shannon-B. Crow Raven over 9 years
    Unfortunately, in my case, ServerCertificateValidationCallback is unavailable. If interested, see Updates 2 and 3 here: stackoverflow.com/questions/27642714/…
  • Sani Singh Huttunen
    Sani Singh Huttunen over 9 years
    See this link for a possible solution.
  • Timo
    Timo over 9 years
    Is there any per-request solution for FtpWebRequest?
  • Nacht
    Nacht about 9 years
    It seems to exist fine in my 4.0
  • The Senator
    The Senator about 9 years
    I think is by far a nicer solution to the 'global' variant, although of course I can understand why you would want it. Personally I favour a request factory which then manages this validation callback. Thanks Adam, nice solution.
  • Fred
    Fred over 8 years
    Returning true is something you can do when experimenting during development, however it is insecure. It should be a conditional.
  • Fred
    Fred over 8 years
    Always returning true is insecure. It should conditionally return true.
  • Fred
    Fred over 8 years
    Always returning true is insecure.
  • Andrej Rommel
    Andrej Rommel over 8 years
    Yes, always trusting all SSL certificates is insecure by definition. Avoid doing so if possible.
  • Mikhail Orlov
    Mikhail Orlov almost 8 years
    This is per-process, so it is not safe.
  • Palec
    Palec about 7 years
    It seems that WebRequest.CreateHttp has been removed after .NET 4.0. var request = (HttpWebRequest)WebRequest.Create(url) is the way to go.
  • Adam Venezia
    Adam Venezia about 7 years
    Using (HttpWebRequest)WebRequest.Create(url) is perfectly valid, but on my box, HttpWebRequest.Create(url) still exists in a project targeting .Net 4.6.2. Chef's choice, but at this point HttpClient is probably the better API to use.
  • aruno
    aruno over 6 years
    Make sure to handle the situation where your alerting mechanism can have an expired cert - or you'll end up with a stackoverflow!
  • Kiquenet
    Kiquenet about 6 years
    What is ProwlUtil.StepReached ?
  • aruno
    aruno about 6 years
    Sorry that’s just my own method to call the Prowl API which can send notifications to my phone. However you want to log it is good. I like to be bugged on my phone for things like this!
  • Kiquenet
    Kiquenet about 6 years
    @AndrejRommel what is your way recommended?
  • Jesse Chisholm
    Jesse Chisholm about 6 years
    Agreed! But then, this OP is about how to ignore them, not trust them.
  • Andrej Rommel
    Andrej Rommel about 6 years
    The recommended way is to create a valid SSL certificate and properly utilize it if you have control over the server. We ended up creating one using letsencrypt.org.
  • Kiquenet
    Kiquenet about 6 years
    Anyways, Using ServicePoint I cannot always trusting all SSL certificates, neither ignore all certificates, because has not ServerCertificateValidationCallback delegate in ServicePoint
  • João Antunes
    João Antunes about 6 years
    In my case, the server's certificate has no trusted CA signing it, and the callback never gets invoked! And I cannot add CA's in an Azure Web App. I have been stuck with this problem for 3 days! any ideas here? stackoverflow.com/questions/49909510/…
  • Adam Venezia
    Adam Venezia about 6 years
    @JoãoAntunes I'm sorry, I don't know how to handle that case.
  • user3290142
    user3290142 over 4 years
    Using the global method, is there a way to reset it so it again validates after setting? The per request answers below will not work in the project I am working on.
  • Sani Singh Huttunen
    Sani Singh Huttunen over 4 years
    @user3290142: ServicePointManager.ServerCertificateValidationCallback = null; should do the trick. Or perhaps store the old callback var oldSCVC = ServicePointManager.ServerCertificateValidationCallback;, change it, make your call and then restore it: ServicePointManager.ServerCertificateValidationCallback = oldSCVC;. Try them out. (Per request obviously uses the request object instead of the global).
  • user3290142
    user3290142 over 4 years
    @SaniSinghHuttunen thanks. I tried what you said but did not have complete success. ServicePointManager.ServerCertificateValidationCallback is null to start with, so there is no initial callback to save off. If I make a connection ignoring SSL, the setting seems to stick regardless of setting the callback to null. If I make a second connection to a different IP and clear the callback, SSL is checked but only for that connection NOT the initial connection.
  • phillyslick
    phillyslick over 4 years
    Won't this only work for .NET Core? (Or whenever ServerCertificateCustomValidationCallback was added to HttpClientHandler)?
  • Sheldon
    Sheldon over 4 years
    This solution should work in .Net Framework 4.5 and later as well as .Net Core (although I have not tested it in .Net Core).
  • Large
    Large almost 4 years
    @Sheldon, this was a gem :) Used in in my localhost api-calls between a .net and a .net core app with success. Nice workaround without accepting all.
  • Alexey Podlasov
    Alexey Podlasov over 3 years
    Upvote this because Unity throws on any get or set of handler.ServerCertificateCustomValidationCallback
  • Sudhakar singh
    Sudhakar singh almost 3 years
    Hi @SaniSinghHuttunen ,I am using this delegate (ServicePointManager.ServerCertificateValidationCallback ) always returning true and suddenly start getting this exception "The request failed. The underlying connection was closed: An unexpected error occurred on a send." , unable to find what causing this. can you please guide in this case?
  • Dan Chase
    Dan Chase over 2 years
    @AndrejRommel Interesting enough I'm getting this with a HttpWebRequest and it's suddenly throwing exceptions related to this, but the cert is good, I wish more articles explained the mechanism behind what HttpWebRequest is validating that others are not, but everything just says to turn it off, which I know is wrong!
  • Daniel Williams
    Daniel Williams about 2 years
    Thank you for the .net core solution!