WCF per connection server certificate validation

前端 未结 7 2881
清歌不尽
清歌不尽 2021-02-20 13:50

I\'m trying to bypass https certificate validation only to our own testing environment (multiple machines), while trying to keep certificate validation for all the other connect

7条回答
  •  自闭症患者
    2021-02-20 14:03

    I was finally able to found a real solution when using .net 4.5.

    This code allows you to use a custom validator only for a specific WCF client.

    It has been tested against BasicHttpBinding with BasicHttpSecurityMode.Transport.

    There is a new property named SslCertificateAuthentication in ClientBase.ClientCredentials.ServiceCertificate.

    You can initialize this property with a X509ServiceCertificateAuthentication where you can provide a custom X509CertificateValidator.

    For example:

    // initialize the ssl certificate authentication
    client.ClientCredentials.ServiceCertificate.SslCertificateAuthentication = new X509ServiceCertificateAuthentication()
    {
       CertificateValidationMode = X509CertificateValidationMode.Custom,
       CustomCertificateValidator = new CustomValidator(serverCert)
    };
    
    // simple custom validator, only valid against a specific thumbprint
    class CustomValidator : X509CertificateValidator
    {
        private readonly X509Certificate2 knownCertificate;
    
        public CustomValidator(X509Certificate2 knownCertificate)
        {
            this.knownCertificate = knownCertificate;
        }
    
        public override void Validate(X509Certificate2 certificate)
        {
            if (this.knownCertificate.Thumbprint != certificate.Thumbprint)
            {
                throw new SecurityTokenValidationException("Unknown certificate");
            }
        }
    }
    

提交回复
热议问题