2015-09-24 91 views
10

我試圖對需要雙向SSL連接(客戶端身份驗證)的服務器進行HTTP調用。我有一個包含多個證書和密碼的.p12文件。請求使用協議緩衝區序列化。HTTPClient的雙向身份驗證

我的第一個想法是將密鑰庫添加到HttpClient使用的WebRequestHandler的ClientCertificate屬性中。我還將密鑰庫添加到我的計算機上受信任的根證書頒發機構。

當PostAsync執行時,我總是收到「無法創建ssl/tls安全通道」。顯然有些事我做錯了,但我在這裏有點失落。

任何指針,將不勝感激。

public void SendRequest() 
    { 
     try 
     { 
      ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; 

      var handler = new WebRequestHandler(); 

      // Certificate is located in bin/debug folder 
      var certificate = new X509Certificate2Collection(); 
      certificate.Import("MY_KEYSTORE.p12", "PASSWORD", X509KeyStorageFlags.DefaultKeySet); 

      handler.ClientCertificates.AddRange(certificate); 
      handler.ServerCertificateValidationCallback = ValidateServerCertificate; 

      var client = new HttpClient(handler) 
      { 
       BaseAddress = new Uri("SERVER_URL") 
      }; 
      client.DefaultRequestHeaders.Add("Accept", "application/x-protobuf"); 
      client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/x-protobuf"); 
      client.Timeout = new TimeSpan(0, 5, 0); 

      // Serialize protocol buffer payload 
      byte[] protoRequest; 
      using (var ms = new MemoryStream()) 
      { 
       Serializer.Serialize(ms, MyPayloadObject()); 
       protoRequest = ms.ToArray(); 
      } 

      var result = await client.PostAsync("/resource", new ByteArrayContent(protoRequest)); 

      if (!result.IsSuccessStatusCode) 
      { 
       var stringContent = result.Content.ReadAsStringAsync().Result; 
       if (stringContent != null) 
       { 
        Console.WriteLine("Request Content: " + stringContent); 
       } 
      } 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine(ex.Message); 
      throw; 
     } 
    } 

     private bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) 
     { 
      if (sslPolicyErrors == SslPolicyErrors.None) 
       return true; 

      Console.WriteLine("Certificate error: {0}", sslPolicyErrors); 

      // Do not allow this client to communicate with unauthenticated servers. 
      return false; 
     } 

編輯

我甚至不闖入ValidateServerCertificate。一旦PostAsync被調用,拋出異常。協議絕對是TLS v1。

客戶端操作系統是Windows 8.1。服務器是用Java編碼(不知道是什麼操作系統運行它的。我沒有訪問它。這是一個黑盒子。)

堆棧跟蹤

在System.Net.HttpWebRequest.EndGetRequestStream( IAsyncResult的asyncResult,TransportContext &上下文) 在System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult的AR)

有沒有內部異常。

+0

誰是存儲在.P12文件中的證書的頒發者?服務器是否信任此類發行人? –

+0

它由我嘗試連接的服務器的所有者發出(他們給我的文件)。 – Mathieu

+0

ValidateServerCertificate返回「true」還是「false」?你可以把一個斷點和檢查?如果它返回false,那麼sslPolocyErrors的值是什麼?試着總是從方法中返回'true'來測試這是否解決了這個問題?也許你的本地機器不信任服務器證書的頒發者? –

回答

0

我認爲這是你需要的東西: Sample Asynchronous SslStream Client/Server Implementation

using System; 
using System.IO; 
using System.Net; 
using System.Threading; 
using System.Net.Sockets; 
using System.Security.Cryptography; 
using System.Security.Cryptography.X509Certificates; 
using System.Net.Security; 


class Program 
{ 
    static void Main(string[] args) 
    { 
     SecureTcpServer server = null; 
     SecureTcpClient client = null; 

     try 
     { 
      int port = 8889; 

      RemoteCertificateValidationCallback certValidationCallback = null; 
      certValidationCallback = new RemoteCertificateValidationCallback(IgnoreCertificateErrorsCallback); 

      string certPath = System.Reflection.Assembly.GetEntryAssembly().Location; 
      certPath = Path.GetDirectoryName(certPath); 
      certPath = Path.Combine(certPath, "serverCert.cer"); 
      Console.WriteLine("Loading Server Cert From: " + certPath); 
      X509Certificate serverCert = X509Certificate.CreateFromCertFile(certPath); 

      server = new SecureTcpServer(port, serverCert, 
       new SecureConnectionResultsCallback(OnServerConnectionAvailable)); 

      server.StartListening(); 

      client = new SecureTcpClient(new SecureConnectionResultsCallback(OnClientConnectionAvailable), 
       certValidationCallback); 

      client.StartConnecting("localhost", new IPEndPoint(IPAddress.Loopback, port)); 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine(ex);    
     } 

     //sleep to avoid printing this text until after the callbacks have been invoked. 
     Thread.Sleep(4000); 
     Console.WriteLine("Press any key to continue..."); 
     Console.ReadKey(); 

     if (server != null) 
      server.Dispose(); 
     if (client != null) 
      client.Dispose(); 

    } 

    static void OnServerConnectionAvailable(object sender, SecureConnectionResults args) 
    { 
     if (args.AsyncException != null) 
     { 
      Console.WriteLine(args.AsyncException); 
      return; 
     } 

     SslStream stream = args.SecureStream; 

     Console.WriteLine("Server Connection secured: " + stream.IsAuthenticated); 



     StreamWriter writer = new StreamWriter(stream); 
     writer.AutoFlush = true; 

     writer.WriteLine("Hello from server!"); 

     StreamReader reader = new StreamReader(stream); 
     string line = reader.ReadLine(); 
     Console.WriteLine("Server Recieved: '{0}'", line == null ? "<NULL>" : line); 

     writer.Close(); 
     reader.Close(); 
     stream.Close(); 
    } 

    static void OnClientConnectionAvailable(object sender, SecureConnectionResults args) 
    { 
     if (args.AsyncException != null) 
     { 
      Console.WriteLine(args.AsyncException); 
      return; 
     } 
     SslStream stream = args.SecureStream; 

     Console.WriteLine("Client Connection secured: " + stream.IsAuthenticated); 

     StreamWriter writer = new StreamWriter(stream); 
     writer.AutoFlush = true; 

     writer.WriteLine("Hello from client!"); 

     StreamReader reader = new StreamReader(stream); 
     string line = reader.ReadLine(); 
     Console.WriteLine("Client Recieved: '{0}'", line == null ? "<NULL>" : line); 

     writer.Close(); 
     reader.Close(); 
     stream.Close(); 
    } 

    static bool IgnoreCertificateErrorsCallback(object sender, 
     X509Certificate certificate, 
     X509Chain chain, 
     SslPolicyErrors sslPolicyErrors) 
    { 
     if (sslPolicyErrors != SslPolicyErrors.None) 
     { 

      Console.WriteLine("IgnoreCertificateErrorsCallback: {0}", sslPolicyErrors); 
      //you should implement different logic here... 

      if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) != 0) 
      { 
       foreach (X509ChainStatus chainStatus in chain.ChainStatus) 
       { 
        Console.WriteLine("\t" + chainStatus.Status); 
       } 
      } 
     } 

     //returning true tells the SslStream object you don't care about any errors. 
     return true; 
    } 
} 
3

你嘗試改變你security protocolSsl3?無論哪種情況,您都需要將Expect財產設置爲true。它會解決你的錯誤。此外,您可以探索this link以獲取有關通過客戶端證書進行身份驗證的更多知識。

public void SendRequest() 
{ 
    try 
    { 
     ServicePointManager.Expect100Continue = true; 
     ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3; 

     var handler = new WebRequestHandler(); 
     ..... 
    } 
    .. 
} 
+0

感謝您的建議。我曾嘗試過,但我仍然遇到了與原始帖子中提到的相同的錯誤。 – Mathieu

0

你試過下面的代碼嗎?

ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true); 

請您它的代碼

handler.ClientCertificates.AddRange(certificate); 
1

我試圖驗證安全協議前行,當我遇到這個職位後來被使用。我發現在使用不正確的安全協議時,我在ValidateServerCertificate之前拋出一個錯誤。 (IIS 7.x默認爲SSL3。)要覆蓋要使用的協議的所有基礎,您可以定義全部。 System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12 | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls | System.Net.SecurityProtocolType.Ssl3;

0

我使用相同的代碼庫爲你,但不是使用

certificate.Import("MY_KEYSTORE.p12", "PASSWORD", X509KeyStorageFlags.DefaultKeySet); 

我使用X509KeyStorageFlags.UserKeySet

還我已經安裝了根證書中的currentUser/CA和工作爲了我。