调用嵌入了 p12 证书的第三方 rest api

Calling 3rd party's rest api embedded with p12 certificate

提问人:hakohako 提问时间:6/6/2023 最后编辑:Brian Tompsett - 汤莱恩hakohako 更新时间:7/15/2023 访问量:97

问:

我已经找了好几天了,但找不到解决方案。我有一个用 C# 编写的 API。我必须使用JSON输入从URL调用第三方的rest API,但我必须使用第三方的p12证书才能调用他们的API。

我找到了一些代码,我尝试了所有代码,但我无法实现。

  1. 我应该将 p12 证书安装到我的本地计算机(或任何调用第三方 API 的服务器)可信存储中,还是可以将其嵌入到“api 调用者”代码中?(我已经安装到本地机器上)

  2. 以下代码引发了该错误:

    {“远程服务器返回错误:(500) 内部服务器错误。

      string URL = ConfigurationManager.AppSettings["GivenApiUrl"];
      var certFile = Path.Combine(@"Given P12 certificate path", " Given_P12_certificate_name.p12");
    
      X509Certificate2 certificate = new X509Certificate2(certFile, "password");

      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
      request.Timeout = 20000;
      request.ContentType = "application/json";
      request.ClientCertificates.Add(certificate);
      request.UserAgent = "TEST";
      request.Method = "POST";

      using (var streamWriter = new StreamWriter(requ.GetRequestStream()))
      {
    string json = "{\"Check\":{\"Id\":\"Tst123\",\"Tkn\":{\"Id\":\"ABCDEFG\"},\"Obj\":\"123456\"}}";
    streamWriter.Write(json);
      }
     
      HttpWebResponse response = (HttpWebResponse) request.GetResponse();

你能帮我吗?

我需要使用 P12 证书调用第三方的 API。

C# REST HTTPWebRequest 调用

评论


答:

0赞 hakohako 6/15/2023 #1

我自己找到了解决方案:

我将 p12 证书文件设置到我的本地计算机(调用第三方 api 的机器)信任存储(我不确定是否有必要),成功的运行代码是:

string "3rd party url here";
var certFile = Path.Combine(@"C:\certificate path here", 
"certificate_name.p12");
X509Certificate2 cert = new X509Certificate2(certFile, "password");
var clientCertificates = new X509CertificateCollection() { cert };

var options = new RestClientOptions(URL)
{
ClientCertificates = clientCertificates
};

var client = new RestClient(options); //This the way to add certificate 
                                        to RestClient

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

var restRequest = new RestRequest();

restRequest.Method = Method.Post;

restRequest.AddHeader("Cache-Control", "no-cache");
restRequest.AddHeader("Accept", "application/json");
Request.AddHeader("Content-Type", "application/json");

string json = "{\"xxxxx\":{\"yyyyy\":\"Blablabla\",\"zzzzz\": 
   {\"wwwww\":\"Blablabla\"},\"qqqqq\":\" Blablabla \"}}";  // My json input here

restRequest.AddParameter("application/json", json, ParameterType.RequestBody);

var response = client.Execute(restrequest);