2015-09-24 59 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和工作为了我。