【发布时间】:2017-12-05 22:17:15
【问题描述】:
我正在努力与提供与 cURL 一起使用的示例代码的第三方集成。我已经能够通过以下命令使用 cURL 成功连接:
curl -k -d "grant_type=client_cert" --basic -u "myUserName:myPassword" -H "Content-Type: application/x-www-form-urlencoded" --cert c:\certs\myCert. pemhttps://vendorUrl/method
在阅读 cURL 文档时,我相信这就是所有开关的含义:
- -k: 不安全(即使连接不安全也继续)
- -d:数据。还表明这是一个 POST。
- --basic: 基本认证
- -u 用户名/密码
- -H 附加标头
- --cert:通过证书
我已经尝试了很多(!)我在网上找到的不同技巧,所以有些代码行可能是不必要的。我试图指出我在代码 cmets 中将 cURL 切换到 C# 的位置。
//Not sure if these are needed or not.
ServicePointManager.Expect100Continue = true;
ServicePointManager.CheckCertificateRevocationList = false;
//allow every possible protocol for now just to eliminate the protocol as the source of the problem
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;
//this should be the equivalent of cURL's "-k" (insecure) switch.
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
var certificatePath = ConfigurationManager.AppSettings.GetValue("myPath");
var clientKey = "myKey";
var clientSecret = "mySecret";
var url = "https://vendorUrl/method";
//create the request
var request = new RestRequest(Method.POST);
////this should be the equivalent of cURL's -d (data) switch. no idea if this is done correctly. I have also tried adding this as "AddJsonBody()"
var body = "grant_type=client_cert";
request.AddBody(body);
//this should be the equivalent of cURL's "-H" (header) switch
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
//Import certificate
var certificates = new X509Certificate();
certificates.Import(certificatePath);
var client = new RestClient
{
BaseUrl = new Uri(url),
//this should be the equivalent of cURL's "--cert" switch
ClientCertificates = new X509CertificateCollection { certificates },
//this should be the equivalent of cURL's "--basic" (Basic Auth) switch and the "-u" switch
Authenticator = new HttpBasicAuthenticator(clientKey, clientSecret)
};
var response = client.Execute(request);
我收到的错误消息是可怕的“请求被中止:无法创建 SSL/TLS 安全通道。”
我还添加了如下所述的跟踪日志记录:The request was aborted: Could not create SSL/TLS secure channel。
我真的不知道如何解析跟踪的输出,但是跟踪中的最后一条消息看起来有问题:
System.Net 信息:0 : [9232] InitializeSecurityContext(In-Buffers count=2, Out-Buffer length=0, returned code=IllegalMessage)。
【问题讨论】:
-
RestSharp 不做任何事情来支持 SSL,无论是自签名的还是真实的。我们只需创建一个
WebRequest。因此,如果您可以设法使其与WebRequest一起使用-它将与RestSharp 一起使用...我知道这不是很有帮助,但仍然如此。