Jerry Bian
Jerry Bian

Reputation: 4238

HttpClient call HTTPS WebApi with self-signed certificate

In our development stage, we created a self-signed certificate, which means I have .cer and .pfx file. When we tried to call the APIs, is there any methods we can use to embed above files in the HTTPS request, so that not every client install the certificate to local trusted certificate store.

Is this possible? I found some APIs which seems like we can do like that, but just cannot get it succeed:

try
{
    var secure = new SecureString();
    foreach (char s in "password")
    {
        secure.AppendChar(s);
    }

    var handler = new WebRequestHandler();
    handler.ClientCertificateOptions = ClientCertificateOption.Manual;
    handler.UseProxy = false;

    var certificate = new X509Certificate2(@"C:\httpstest2.pfx", secure);
    handler.ClientCertificates.Add(certificate);

    using (var httpClient = new HttpClient(handler))
    {
        httpClient.BaseAddress = new Uri("https://www.abc.com");
        var foo = httpClient.GetStringAsync("api/value").Result;
        Console.WriteLine(foo);
    }
}
catch (Exception ex)
{
    Console.WriteLine(ex);
}
  1. Do I need to use X509Certificate instead of X509Certificate2?
  2. If we purchase real certificate from 3rd-party company, can we just go through the validate exception without caring about the certificate issue?

Upvotes: 1

Views: 7721

Answers (2)

MvdD
MvdD

Reputation: 23436

Clients only need the public key in the .cer file, which is sent automatically when the https connection is established. But whether the client trusts that certificate is not a decision the server sending the cert should be allowed to make.

You can use a group policy to distribute the certificate to your clients. See http://technet.microsoft.com/en-us/library/cc770315(v=ws.10).aspx for more details.

Upvotes: 0

SpeedOfSpin
SpeedOfSpin

Reputation: 1691

Can you just use this code to ignore any SSL errors

ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

Obviously make sure this doesn't make it to production.

Upvotes: 4

Related Questions