How to call the default certificate check when overriding ServicePointManager.ServerCertificateValidationCallback in C#?

前端 未结 3 1321
死守一世寂寞
死守一世寂寞 2021-01-01 18:43

I need to trust some self-signed certificates in the application, so I override validation callback like this:

ServicePointManager.ServerCertificateValidation         


        
3条回答
  •  渐次进展
    2021-01-01 19:23

    It's less difficult than you think to walk the chain from within your callback.

    Have a look at http://msdn.microsoft.com/en-us/library/dd633677(v=exchg.80).aspx

    The code in that sample examines the certificate chain to work out if the certificate is self-signed and if so, trust it. You could adapt that to accept a PartialChain instead or as well. You'd be looking to do something like this:

    if (status.Status == X509ChainStatusFlags.PartialChain ||
        (certificate.Subject == certificate.Issuer &&
         status.Status == X509ChainStatusFlags.UntrustedRoot)
    {
        // Certificates with a broken chain and
        // self-signed certificates with an untrusted root are valid. 
        continue;
    }
    else if (status.Status != X509ChainStatusFlags.NoError)
    {
        // If there are any other errors in the certificate chain,
        // the certificate is invalid, so the method returns false.
        return false;
    }
    

    Alternatively, inspect the Subject property:

    private static bool CertificateValidationCallBack(
        object sender,
        System.Security.Cryptography.X509Certificates.X509Certificate certificate,
        System.Security.Cryptography.X509Certificates.X509Chain chain,
        System.Net.Security.SslPolicyErrors sslPolicyErrors)
    {
        return certificate.Subject.Contains(".dsoduc.com");
    }
    

提交回复
热议问题