Calling a php webservice from .net with a cert
I'm using this code from c# to call a php web service that is secured by user/password and certificate:
string wsurl = ConfigurationManager.AppSettings["Url"];
string wsuser = ConfigurationManager.AppSettings["User"];
string wspass = ConfigurationManager.AppSettings["Pass"];
string url = string.Format(wsurl, param1, param2);
System.Net.CredentialCache oCredentialCache = new System.Net.CredentialCache();
oCredentialCache.Add(new System.Uri(url), "Basic",
new System.Net.NetworkCredential(wsuser, wspass));
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Timeout = TIMEOUT;
req.Credentials = oCredentialCache;
req.Method = "GET";
AttachCert(req);
//Get the data as an HttpWebResponse object
WebResponse resp = req.GetResponse();
This works as expected when run from my devel machine but when we upload this to the server I get a Timeout error on the call to GetResponse().
The AttachCert() call is where I attach the certificate to the request, and if I comment this line I don't get the timeout but a correct error saying the call could not be completed because of the missing certificate. This is the AttachCert code:
public static void AttachCert(HttpWebRequest Request)
{
// Obtain the certificate.
string certpath = ConfigurationManager.AppSettings["CertPath"];
X509Certificate Cert = X509Certificate.CreateFromCertFile(certpath);
ServicePointManager.CertificatePolicy = new CertPolicy();
Request.ClientCertificates.Add(Cert);
}
A开发者_如何学Cny idea why this would work on my machine but not on the server? We tried to remove the certificate on the webservice and the it worked as expected. So there's clearly something strange on that call but I cannot figure what.
Thanks Vicenç
Try registering this callback and watch for any errors.
public static bool ValidateRemoteCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors) {
// check for errors
// just return true to accept any certificate (self signed etc)
}
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(MyClass.ValidateRemoteCertificate);
I hope it helps.
精彩评论