Dot-Net

如何將“ServerCertificateValidationCallback”屬性設置回其預設行為?

  • August 26, 2020

我在單個方法中使用以下程式碼行來顯式檢查和信任來自以下主機的 SSL 證書:MyTrustedCompany.com:

ServicePointManager.ServerCertificateValidationCallback = Function(obj As [Object], certificate As X509Certificate, chain As X509Chain, errors As SslPolicyErrors) (certificate.Subject.Contains("CN=MyTrustedCompany.com"))

程式碼沒問題-> 100% 完美執行。

問題是,它太遠了。我認為它的範圍只會在我貼花它的方法內,但顯然它是“ServicePointManager”對像上的一個共享屬性,並且必須在整個應用程序中持續存在,這是我不想要的。

問題是後來我正在呼叫我的 Web 服務等,並得到“無法建立信任關係……”異常。這是因為在上面的程式碼行中,我檢查了特定於該方法的 SSL 證書的主機名。我快速測試了從回調中返回“真”,因此所有證書都將受到信任,而不是檢查特定名稱(即 MyTrustedCompany)和後續請求是否有效。這就是我知道這個回調分配比那個單一方法到達父親的方式。當然,我可以擴展回調以包含所有其他證書名稱,但我更願意“ServerCertificateValidationCallback”設置回其預設行為。就像下面的虛擬碼:

ServicePointManager.ServerCertificateValidationCallback = Nothing  'Default checking behavior

如何刪除自定義驗證並將其設置回其預設行為?謝謝!

這實際上似乎有效(就像它一樣簡單)並使對像以其預設方式執行。

ServicePointManager.ServerCertificateValidationCallback = Nothing

您只希望為某些 URL 返回 true,但除此之外,這可以滿足您的要求,從而可以使用多個委託。每個回調的邏輯可以包括通過反射進行檢查,以便回調僅在從某些組件呼叫時返回 true,從而在某些 URL 和某些應用程序之間創建一種隧道。

使用此程式碼的一種方法: 1. 在對像生命週期的早期定義 mIgnoreBadCertificates 委託 2. 將包含“beSecure”程式碼的屬性設置為 true 3. 發送 Http 請求。4. 將屬性設置為 false。這是非常重要的,並且應該以保證它被呼叫的方式實現。IDisposable 模式是一種選擇。

private System.Net.Security.RemoteCertificateValidationCallback mIgnoreBadCertificates = new
   System.Net.Security.RemoteCertificateValidationCallback(
     delegate { return true; });

if (beSecure)
   {   //require secure communications
       System.Net.ServicePointManager.ServerCertificateValidationCallback -= mIgnoreBadCertificates;
       Iwds.EventLogger.LogVeryFrequentEvent("Requiring Good Certificates from Remote Sites");
   }
   else
   {   /// Allow connections to SSL sites that have unsafe certificates.
       System.Net.ServicePointManager.ServerCertificateValidationCallback += mIgnoreBadCertificates;
       Iwds.EventLogger.LogVeryFrequentEvent("Ignoring Bad Certificates from Remote Sites");
   }

引用自:https://stackoverflow.com/questions/4156365