Add certificate on request with RestSharp

后端 未结 1 1053
南笙
南笙 2020-12-09 11:55

I\'m trying to communicate with a server. This server send me a certificate and a private key in order to execute my request successfully.

To test the server, I use

相关标签:
1条回答
  • 2020-12-09 12:20

    Ok, I got the solution.

    First of all, I had to stop using the .crt and the .key for the certificate. I have to get a .pfx. This can be done with openssl command (openssl documentation)

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

    After creating the certificate, just add it to the request like this

    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);
    
    0 讨论(0)
提交回复
热议问题