WCF证书链,以编程方式验证

Ste*_*eve 7 c# certificate x509

我试图以编程方式使用证书,而不是使用商店.我X509Certificate2用文件名和密码创建了.

当我手动将根证书添加到受信任人员中的证书存储区时,这可以正常工作.但是,我宁愿不必在每次部署时都这样做 - 我宁愿以编程方式处理它.

当我从证书存储中删除根证书时,我得到一个例外.

我读过的所有内容似乎都说我必须手动将根证书添加到证书库,否则信任链将无效.

问题:是否有编程方式来设置信任链,所以我不必手动完成它?

代码如下:

        var serverCert = new X509Certificate2("FullPathToMyCertificate.cer", "Password");
        Client.ClientCredentials.ServiceCertificate.DefaultCertificate = serverCert;
Run Code Online (Sandbox Code Playgroud)

我尝试使用客户端时发生的异常是:

System.IdentityModel.Tokens.SecurityTokenValidationException 

The X.509 certificate CN=notrealcertname, OU=TPA, OU=BMP, OU=Projects, O=Somebody, C=US is not in the trusted people store. 
The X.509 certificate CN=notrealcertname, OU=TPA, OU=BMP, OU=Projects, O=Somebody, C=US chain building failed. 
The certificate that was used has a trust chain that cannot be verified. 
Replace the certificate or change the certificateValidationMode. 
A certificate chain could not be built to a trusted root authority.
Run Code Online (Sandbox Code Playgroud)

Yah*_*hia 4

使用的组件默认验证链 - 当无法验证链时,您会收到该异常。如果您想做所有事情,包括在代码中验证链,那么您需要实现“自定义验证”并将其集成到 WCF 主机中

Client.ServiceCertificate.Authentication.CertificateValidationMode =
              X509CertificateValidationMode.Custom;
Client.ServiceCertificate.Authentication.CustomCertificateValidator =
    new MyCertificateValidator();
Run Code Online (Sandbox Code Playgroud)

另一种选择是完全禁用验证(不适用于生产!!!

Client.ServiceCertificate.Authentication.CertificateValidationMode =
              X509CertificateValidationMode.None;
Run Code Online (Sandbox Code Playgroud)

编辑-评论后:

为了自己验证链,您应该看看X509ChainX509Store - 要了解如何实现这样的链验证,请查看Mono 的实现...Verify基本上,您使用该Find方法来搜索父级的X509Certificate2Collection等等...自定义验证的验证标准取决于您(有效签名,未过期...)。

MSDN 上的一些参考链接: