2011-08-25 112 views
7

我試圖以編程方式使用證書,而不是使用存儲。我正在創建X509Certificate2的文件名和密碼。WCF證書鏈,通過編程驗證

當我手動將根證書添加到受信任的人的證書存儲區時,這可以正常工作。但是,我寧願不必在每次部署時都這樣做 - 我寧願以編程方式處理它。

當我從證書存儲中刪除根證書時,出現異常。

我已閱讀的一切似乎都說我必須手動將根證書添加到證書存儲區,否則信任鏈將無法工作。

問:是否有編程方式來設置信任鏈,因此我不必手動執行此操作?

代碼如下:

 var serverCert = new X509Certificate2("FullPathToMyCertificate.cer", "Password"); 
     Client.ClientCredentials.ServiceCertificate.DefaultCertificate = serverCert; 

例外,當我嘗試使用客戶端這occures是:

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. 

回答

4

所使用的組件在默認情況下驗證鏈 - 當鏈條無法驗證你得到的例外。 如果你想要做的一切,包括在代碼中鏈的驗證,那麼你需要implement "custom validation" and integrate that into the WCF Host

Client.ServiceCertificate.Authentication.CertificateValidationMode = 
       X509CertificateValidationMode.Custom; 
Client.ServiceCertificate.Authentication.CustomCertificateValidator = 
    new MyCertificateValidator(); 

另一種辦法是禁用完全驗證(不用於生產!!!

Client.ServiceCertificate.Authentication.CertificateValidationMode = 
       X509CertificateValidationMode.None; 

編輯 - 後評論:

用於驗證鏈接自己,你應該看看X509ChainX509Store - 瞭解如何實現這樣一個鏈式驗證可以看看VerifyMono's implementation ...基本上你使用Find方法來搜索X509Certificate2Collection父母等在...驗證標準與自定義驗證由您決定(有效簽名,未過期...)。

在MSDN一些參考鏈接:

+0

非常感謝的快速反應,葉海亞。那麼,假設我想實現一個** CustomCertificateValidator **,它模仿了當我不使用** CustomCertificateValidator **時發生的默認行爲,但是已經手動將根證書添加到了Trusted People中的證書存儲區。我會在我的** CustomCertificateValidator **中放什麼?據推測,默認行爲是針對受信任的人中的根證書評估** serverCert **,並確定其是否正確,並讓客戶端收到響應。它做什麼做這個評估?再次謝謝,史蒂夫。 – Steve

+0

客戶在這裏提到什麼(比如在Client.ServiceCertificate中),請問有空嗎?非常感謝。 – iTSrAVIE

+1

這不是一個命名空間。此代碼假設它位於派生自System.ServiceModel.ClientBase <>的類中,並且此「ClientBase」公開了一個簡單的「ClientCredentials」屬性,您可以在其中執行'.ServiceCertificate'然後'.Authentication'然後'。 CertificateValidationMode「等。如果您需要確切地知道,ServiceCertificate是一個類X509CertificateRecipientClientCredential – quetzalcoatl