Skip to content

Instantly share code, notes, and snippets.

@wislon
Created February 22, 2013 12:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wislon/5013030 to your computer and use it in GitHub Desktop.
Save wislon/5013030 to your computer and use it in GitHub Desktop.
Web API HttpClient SSL demo (concept only - using extremely naiive server SSL certificate validation)
// See:
// http://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/d80eb3c7-8d1b-4284-a157-ba415cfbcc14 (taicomjp's solution)
// http://blog.aggregatedintelligence.com/2010/06/wcf-ssl-certificates-and-certificate.html
// http://msdn.microsoft.com/en-us/library/system.net.security.remotecertificatevalidationcallback.aspx
// also see http://www.iis.net/learn/manage/configuring-security/how-to-set-up-ssl-on-iis
// to quickly set up a test certificate on a local website in IIS
// All this does is happily accept any certificate thrown at it, regardless of whether it's got the right
// domain name, etc.
// you'll need to add references/usings for:
//System.Net
//System.Net.Security
//System.Security.Cryptography.X509Certificates
// This is designed to work from LinqPad, so you'll have to wrap it properly if you want it to
// work as a console app or something.
void Main()
{
System.Net.ServicePointManager.ServerCertificateValidationCallback =
new System.Net.Security.RemoteCertificateValidationCallback(ValidateServerCertificate);
// the actual certificate check is left to us.
var client = SetupNewHttpClient();
HttpResponseMessage response = client.GetAsync("api/values").Result;
response.EnsureSuccessStatusCode();
var result = response.Content.ReadAsAsync<string[]>().Result;
result.Dump();
}
// Define other methods and classes here
public static bool ValidateServerCertificate(object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
return true;
// if (sslPolicyErrors == SslPolicyErrors.None) return true;
//
// Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
//
// // Do not allow this client to communicate with unauthenticated servers.
// return false;
}
private HttpClient SetupNewHttpClient()
{
//const string baseUrl = "http://localhost:800/";
const string baseUrl = "https://localhost:4430/"; // set up a new dummy website with a self-signed cert here, note the port.
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(baseUrl);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return client;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment