Skip to content

Instantly share code, notes, and snippets.

@haydosw
Last active September 23, 2016 05:19
Show Gist options
  • Save haydosw/4cdd3b45314e4e7bd325bf4375191838 to your computer and use it in GitHub Desktop.
Save haydosw/4cdd3b45314e4e7bd325bf4375191838 to your computer and use it in GitHub Desktop.
private static X509Certificate2 GetIISExpressCertificateFromLocalStore()
{
// http://stackoverflow.com/questions/1742938/how-to-solve-could-not-establish-trust-relationship-for-the-ssl-tls-secure-chan
ServicePointManager.ServerCertificateValidationCallback += (se, cert, chain, sslerror) => true;
var store = new X509Store(StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
var certs = store.Certificates.Find(X509FindType.FindBySubjectName, "localhost", false);
if (certs.Count == 0)
{
throw new Exception($"Cannot find localhost cert");
}
store.Close(); // Using block was failing - but its idisposable
// By now we have at least one cert that matches thumb - use it
// If i get 2 and it starts using the wrong cert - Fix the store...
return certs[0];
}
static void Main(string[] args)
{
var authCert = new X509Certificate2("J:\\Export.cer");
var tlsCert = GetIISExpressCertificateFromLocalStore();
var requestHandler = new WebRequestHandler();
requestHandler.ClientCertificates.Add(authCert);
requestHandler.ClientCertificates.Add(tlsCert);
requestHandler.ServerCertificateValidationCallback += (sender, certificate, chain, errors) => true;
var client = new HttpClient(requestHandler)
{
BaseAddress = new Uri("https://localhost:44365/"),
};
var response = client.GetAsync("api").Result; // Ew
var responseContent = response.Content.ReadAsStringAsync().Result; // Ew
Console.WriteLine(responseContent);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment