我正在努力与提供与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。 pem https://vendorUrl/method
在阅读cURL文档时,我相信这是所有开关转换为:
我尝试了很多(!)我在网上找到的不同提示,因此有些代码可能是不必要的。我试图在我的代码注释中指出我将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,返回代码= IllegalMessage)。
答案 0 :(得分:0)
在我的情况下,我必须在本地计算机/服务器上安装证书才能使其正常工作。我不清楚为什么cURL在没有安装证书的情况下工作。
我必须安装的证书有.p12扩展名。所以在代码中我加载了.pem文件,这是一个从.p12文件派生的文件。我并不是在理解为什么。
通过切换到HttpClient,我可以通过添加以下内容来避免加载.pem文件:
String
我无法找到与ClientCertificateOptions等效的RestSharp / WebRequest。