我试图只对我们自己的测试环境(多台机器)绕过 https 证书验证,同时尝试对所有其他连接保持证书验证。
从在线阅读来看,大多数(如果不是全部)WCF 相关建议似乎指向以下类似内容
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
但是,这是一个全局设置,我只想将其应用于特定连接。这甚至可能/支持的使用场景吗?
最佳答案
在使用 .net 4.5 时,我终于找到了一个真正的解决方案。
此代码允许您仅为特定的 WCF 客户端使用自定义验证器。
它已经通过 BasicHttpSecurityMode.Transport
针对 BasicHttpBinding 进行了测试。
有一个名为 SslCertificateAuthentication
的新属性在 ClientBase.ClientCredentials.ServiceCertificate
中。
您可以使用 X509ServiceCertificateAuthentication
初始化此属性您可以在其中提供自定义 X509CertificateValidator
。
例如:
// 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");
}
}
}
关于c# - WCF 每个连接服务器证书验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20431764/