HTTPS and trusting server certificates

If you making HttpWebRequest calls to secure servers, using HTTPS you’ll probably come across a situation where the server request fails. There can be a number of reasons for this – sometimes you might be using a test certificate which has no trusted root, or your using your own certificate authority which isn’t in the trusted root certificate store on the PC you’re running the tests from. Well you can override the policy, to accept specific certificates, or a blanket cover-all to accept all certificates.

For more information see the MSDN Library page.

Place this somewhere before you start making HttpWebRequest jobs, and define the class.

System.Net.ServicePointManager.CertificatePolicy = new TrustedCertificatePolicy();

Then define this class. You can change the CheckValidationResult function to check for different problems, such as expired certificates, untrusted certificate authority etc. Return true if you want to trust the certificate, and false if you don’t want to.

public class TrustedCertificatePolicy : System.Net.ICertificatePolicy 
    private enum    CertificateProblem  : long
        CertEXPIRED                   = 0x800B0101,
        CertVALIDITYPERIODNESTING     = 0x800B0102,
        CertROLE                      = 0x800B0103,
        CertPATHLENCONST              = 0x800B0104,
        CertCRITICAL                  = 0x800B0105,
        CertPURPOSE                   = 0x800B0106,
        CertISSUERCHAINING            = 0x800B0107,
        CertMALFORMED                 = 0x800B0108,
        CertUNTRUSTEDROOT             = 0x800B0109,
        CertCHAINING                  = 0x800B010A,
        CertREVOKED                   = 0x800B010C,
        CertUNTRUSTEDTESTROOT         = 0x800B010D,
        CertREVOCATION_FAILURE        = 0x800B010E,
        CertCN_NO_MATCH               = 0x800B010F,
        CertWRONG_USAGE               = 0x800B0110,
        CertUNTRUSTEDCA               = 0x800B0112

    public TrustedCertificatePolicy() {}

    public bool CheckValidationResult
        System.Net.ServicePoint sp,
        System.Security.Cryptography.X509Certificates.X509Certificate certificate,
        System.Net.WebRequest request, int problem)
        if( Enum.IsDefined(typeof(CertificateProblem), problem) )
            CertificateProblem p = (CertificateProblem)problem;

        return true;

2 thoughts on “HTTPS and trusting server certificates”

  1. Hi,
    This article is really informative. Thanks for the valuable piece of information.
    I need some more info : I did exactly what you have specified. Now I am getting a different error – Unable to create transport creation. Any idea whats happening?

    Thanks in advance

  2. Can’t find any help on google with that error message. Is it intermittent? Make sure you are closing the response each time. Can you tell me the exact error message?

Comments are closed.