Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpClient certificate when hosted in IIS/Asp.NET Application not work

I have a strange problem. I need to perform an SSL request using a CER client certificate, to a server that requires authentication by that certificate.

I am using the code below:

   var cert = X509Certificate.CreateFromCertFile("cert.cer");

   var handler = new WebRequestHandler();
   handler.ClientCertificates.Add(cert);

   var http_client = new HttpClient(handler);
   http_client.BaseAddress = new Uri("https://service.com/");

   var str_json = JsonConvert.SerializeObject(new
   {
       Field = "Value1",
       Fiesl2 = "Value2"
   });

   var byteContent = new ByteArrayContent(Encoding.UTF8.GetBytes(str_json));
   byteContent.Headers.Remove("Content-Type");
   byteContent.Headers.Add("Content-Type", "application/json");

   var res = http_client.PostAsync("ResourcePath", byteContent).Result;

   res.EnsureSuccessStatusCode(); //THe error 401 ocurrs here

   var res_body = res.Content.ReadAsStringAsync().Result;

This code works perfectly when I squeeze into a ConsoleApplicaiton or a WebApplication in IIS Express.

But when I squeeze exactly the same code in Local IIS or IIS Server, I get the 401-Unauthorized error. The strange thing is that using Fiddler, in this case I can not even see the request attempt.

I've already checked that path is not the problem. The problem occours in .NET 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1 and etc..

Can anyone help me out, is it any configuration that should be performed in IIS. I've researched a lot, but I did not find that specific error.

like image 210
Fabio Avila Avatar asked Feb 18 '26 15:02

Fabio Avila


1 Answers

A .cer file at client side does not contain private key, so usually it won't work if mutual SSL/TLS is required by the server. You need to get a valid certificate with private key (usually a .pfx file).

like image 166
Lex Li Avatar answered Feb 20 '26 03:02

Lex Li



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!