Help with HTTPWebRequest and client certificates

N

nomad

Hi,

I am using HTTPWebRequest to add a client certificate. I am then
using HTTPWebRequest to POST xml to a web service which requires the
attached client certificate to authenticate with their server
certificate. However, I keep getting an error "Unable to connect to
remote server". I know I am able to connect to their server and
retrieve an XML response as we were able to do this using our old
solution (WinHTTP in Visual Basic 6). I have read many articles and
some of them have mentioned ignoring all certificate errors which I am
also doing but with no luck. If anyone has any suggestion it would be
greatly appreciated. The code to add the certificate is below.

webRequest.ClientCertificates.Add(GetCertificate());

private X509Certificate GetCertificate()
{
///Set store to LocalMachine as this is where the
certificates must be installed
X509Store store = new X509Store(StoreName.My,
StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
//Find certificate based on it's name
X509Certificate2Collection certificates =
store.Certificates.Find(X509FindType.FindBySubjectName, this.sslName,
true);
return certificates[0];


}

The code to ignore certificate errors is below:

ServicePointManager.ServerCertificateValidationCallback =
new
RemoteCertificateValidationCallback(IgnoreCertificateErrorHandler);

private bool IgnoreCertificateErrorHandler(object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
//I would log a Information Error so we know if partner
site is iffy on the security side
//But for now, as simple skip error will do
return true;
}

Sending the XML is below. It fails on using (Stream os =
this.webRequest.GetRequestStream())

public string Send(string dataToSend)
{
//Convert our string to a byte array
byte[] bytes = Encoding.ASCII.GetBytes(dataToSend);
this.webRequest.ContentLength = bytes.Length;

//write bytes to server
using (Stream os = this.webRequest.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}

//Get the response
WebResponse webResponse = webRequest.GetResponse();

if (webResponse != null)
{
using (webResponse)
{
using (StreamReader sr = new
StreamReader(webResponse.GetResponseStream(), Encoding.Default))
{
//return the data as string
return sr.ReadToEnd().Trim();
}
}
}
else //we got no response, we return null
{
return null;
}

}


Thanks
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top