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

前端 未结 3 1301
死守一世寂寞
死守一世寂寞 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:45

    Something like this might work. Note the X509CertificateValidator allows you to choose whether to include the Trusted People store in the validation.

    private static bool CertificateValidationCallBack(
        object sender,
        X509Certificate certificate,
        X509Chain chain,
        SslPolicyErrors sslPolicyErrors)
    {
        // Your custom check here...
        if (isYourSpecialCase)
        {
            return true;
        }
    
        // If it is not your special case then revert to default checks...
    
        // Convert the certificate to a X509Certificate2
        var certificate2 = certificate as X509Certificate2 ?? new X509Certificate2(certificate);
    
        try
        {
            // Choose the type of certificate validation you want
            X509CertificateValidator.PeerOrChainTrust.Validate(certificate2);
            //X509CertificateValidator.ChainTrust.Validate(certificate2);
        }
        catch
        {
            return false;
        }
    
        // Sender is always either a WebReqest or a hostname string
        var request = sender as WebRequest;
        string requestHostname = request != null ? request.RequestUri.Host : (string)sender;
    
        // Get the hostname from the certificate
        string certHostname = certificate2.GetNameInfo(X509NameType.DnsName, false);
    
        return requestHostname.Equals(certHostname, StringComparison.InvariantCultureIgnoreCase);
    }
    

提交回复
热议问题