Add client certificate to .net core Httpclient

Krishna.N picture Krishna.N · Oct 13, 2016 · Viewed 89.5k times · Source

I was playing around with .Net Core and building an API that utilizes payment APIs. There's a client certificate that needs to be added to the request for two-way SSL authentication. How can I achieve this in .Net Core using HttpClient?

I have looked at various articles and found that HttpClientHandler doesn't provide any option to add client certificates.

Please advise

Answer

user1289580 picture user1289580 · Oct 21, 2016

I ran a fresh install for my platform (Linux Mint 17.3) following these steps: https://www.microsoft.com/net/core. I created a new console application targeting the netcoreapp1.0 framework, was able to submit a client certificate; however, I did receive "SSL connect error" (CURLE_SSL_CONNECT_ERROR 35) while testing, even though I used a valid certificate. My error could be specific to my libcurl.

update: I ran the exact same thing on Windows 7 and it worked exactly as needed.

// using System.Net.Http;
// using System.Security.Authentication;
// using System.Security.Cryptography.X509Certificates;

var handler = new HttpClientHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.SslProtocols = SslProtocols.Tls12;
handler.ClientCertificates.Add(new X509Certificate2("cert.crt"));
var client = new HttpClient(handler);
var result = client.GetAsync("https://apitest.startssl.com").GetAwaiter().GetResult();