c# - WCF 每个连接服务器证书验证

标签 c# wcf ssl

我试图只对我们自己的测试环境(多台机器)绕过 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/

相关文章:

C#按升序和降序对数组进行排序

c# - MVC 列表 ViewModel 在表单提交时未绑定(bind)

c# - (尝试)从 WSE 3.0 迁移到 WCF 以获取客户端代码

ESP8266(Arduino 库)中的 SSL - 如何处理证书更改?

c# - .NET 4.5(或 4.5.1)是否能够与安全协议(protocol)无关?

c# - 涉及 List<T> 和对象转换的棘手问题

c# - 选择性地统一解决同一接口(interface)的依赖关系

c# - 如何从 WCF 服务应用程序获取客户端地址?

Azure 上的 WCF 服务

google-chrome - 设置 SSL 后与站点的连接仍然不完全安全