Reputation: 31
I'm trying to make a web request to a 3rd party endpoint using .NET Core 2. The endpoint requires authentication with a client certificate and a username and password. So far everything I try results in a 403 (Forbidden) error. I've tried the following so far:
try
{
var handler = new HttpClientHandler();
handler.Credentials = new NetworkCredential(username, password);
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.SslProtocols = SslProtocols.Tls12;
handler.ClientCertificates.Add(new X509Certificate2(certificate));
var client = new HttpClient(handler);
var result = await client.GetStringAsync(url);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
I've also tried:
try
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var request = (HttpWebRequest)WebRequest.Create(url);
var cert = new X509Certificate2(certificate);
request.ClientCertificates.Add(cert);
request.Credentials = new NetworkCredential(username, password);
request.Method = "GET";
var response = (HttpWebResponse)request.GetResponse();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
So far I'm just trying to do a GET but eventually I'll need to do a POST.
As I said above, both result in a 403. If I run the second sample against the .NET Framework it works just fine. Also, if I have Fiddler running then I get an OK status returned and not a 403.
Any thoughts on what I'm doing wrong that is preventing .NET Core from successfully connecting to an endpoint?
Upvotes: 2
Views: 3892
Reputation: 31
I ended up switching the code to what I have below and that did the trick. I set the ClientCertificateOption to be Automatic and I removed manually specifying the certificate.
try
{
var handler = new HttpClientHandler();
handler.Credentials = new NetworkCredential(username, password);
handler.ClientCertificateOptions = ClientCertificateOption.Automatic;
handler.SslProtocols = SslProtocols.Tls12;
var client = new HttpClient(handler);
var result = await client.GetStringAsync(url);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
Upvotes: 1