【问题标题】:Add certificate on request with RestSharp根据要求使用 RestSharp 添加证书
【发布时间】:2018-08-10 16:08:33
【问题描述】:

我正在尝试与服务器通信。该服务器向我发送证书和私钥,以便成功执行我的请求。

为了测试服务器,我使用Postman。 所以我在邮递员中填写证书设置,我的请求工作正常

现在我想在 C# 中做同样的事情。

为此,我使用RestSharp 来创建请求。

这是我的代码

 var client = new RestClient(url);

 byte[] certBuffer = UtilsService.GetBytesFromPEM(myCertificate, Models.Enum.PemStringType.Certificate);
 byte[] keyBuffer = UtilsService.GetBytesFromPEM(encryptedPrivateKey, Models.Enum.PemStringType.RsaPrivateKey);

 X509Certificate2 certificate = new X509Certificate2(certBuffer, secret);
 client.ClientCertificates = new X509CertificateCollection() { certificate };
 var request = new RestRequest(Method.POST);
 request.AddHeader("Cache-Control", "no-cache");
 request.AddHeader("Accept", "application/json");
 request.AddHeader("Content-Type", "application/json");
 request.AddParameter("myStuff", ParameterType.RequestBody);
 IRestResponse response = client.Execute(request);

请求无效。我认为问题出在我如何在 RestSharp 中加载证书。

我正在寻找如何在 RestSharp 中正确设置证书的信息。

我正在使用 RestSharp,但我可以是任何其他可以在 C# 中工作的东西

【问题讨论】:

  • 不知道你是否在使用它,但 Postman 有一个内置功能,您可以在其中导出大多数知名语言的请求。 C# 恰好是其中之一,它使用 RestSharp 库。只需单击屏幕右上角的代码按钮,然后选择 c#。如果您已经知道这一点,这可能看起来很明显,很抱歉!
  • 是的,我已经通过这种方式生成了代码。但它没有考虑证书......
  • 明白了。抱歉,我希望可以,但我不知道如何为您提供帮助。

标签: c# x509certificate restsharp


【解决方案1】:

好的,我知道了。

首先,我不得不停止使用 .crt 和 .key 作为证书。我必须得到一个.pfx。这可以通过 openssl 命令完成 (openssl documentation)

openssl pkcs12 -export -out certificate.pfx -inkey privateKey.key -in certificate.crt -certfile CACert.crt

创建证书后,只需像这样将其添加到请求中

var client = new RestClient(url);

ServicePointManager.Expect100Continue = true;
ServicePointManager.DefaultConnectionLimit = 9999;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;

var certFile = Path.Combine(certificateFolder, "certificate.pfx");
X509Certificate2 certificate = new X509Certificate2(certFile, onboard.authentication.secret);
client.ClientCertificates = new X509CertificateCollection() { certificate };
client.Proxy = new WebProxy();
var restrequest = new RestRequest(Method.POST);
restrequest.AddHeader("Cache-Control", "no-cache");
restrequest.AddHeader("Accept", "application/json");
restrequest.AddHeader("Content-Type", "application/json");
restrequest.AddParameter("myStuff", ParameterType.RequestBody);
IRestResponse response = client.Execute(restrequest);

【讨论】:

  • +1 问答。我花了一个小时寻找一个简单的解决方案。最后,一些有效的东西。谢谢!!
  • 谢谢,谢谢,谢谢一千次谢谢。为这个非常简单的解决方案寻找和挣扎了几个小时
  • 在我添加这行 System.Net.ServicePointManager.ServerCertificateValidationCallback += (s, cert, chain, sslPolicyErrors) => true; 后这对我有用 - 我希望这对其他人有用。
  • 谢谢!对于那些被卡住也运行命令的人,请将其添加到命令的末尾 -passout pass:myPassWord
  • 我能够使用 .p12 文件而不是 .pfx。 var certFile = Path.Combine("C:\\Projects\\Certs\\", "CERTFILE_SHA2.p12");
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-17
  • 1970-01-01
  • 2023-02-10
  • 2017-05-12
  • 2010-12-08
  • 1970-01-01
相关资源
最近更新 更多