【发布时间】:2015-09-24 20:33:02
【问题描述】:
我正在尝试对需要双向 SSL 连接(客户端身份验证)的服务器进行 HTTP 调用。我有一个包含多个证书和密码的 .p12 文件。使用协议缓冲区对请求进行序列化。
我的第一个想法是将密钥库添加到 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& context) 在 System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar)
没有内在的例外。
【问题讨论】:
-
.P12 文件中存储的证书的颁发者是谁?服务器信任这样的发行者吗?
-
它是由我尝试连接的服务器的所有者发布的(他们给了我文件)。
-
ValidateServerCertificate 是否返回
true或false?你可以设置一个断点并检查吗?如果返回 false,sslPolocyErrors 的值是多少?尝试始终从方法中返回true只是为了测试这是否解决了问题?也许您的本地计算机不信任服务器证书的颁发者? -
您确定服务器使用 TLS 1.0 吗?看看SecurityProtocolType enumeration。您可以使用 SSL、TLS1.0、TLS1.1 或 TLS 1.2
-
我什至没有闯入 ValidateServerCertificate。一旦调用 PostAsync,就会引发异常。至于 SecurityProtocol,我很确定它是 TLS1,但我会再次检查。
标签: c# authentication ssl ssl-certificate httpclient