flofreelance
flofreelance

Reputation: 944

HttpWebRequest with p12 cert + password

I need to be authentificated with p12 cert (with password) + cookie.

Here is my code :

X509Certificate2 certificate = new X509Certificate2();
byte[] rawCertificateData = File.ReadAllBytes(@"C:\mycert.p12");
certificate.Import(rawCertificateData, "c3rtifPassw0rd", X509KeyStorageFlags.PersistKeySet);

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://apidomain.com/getDatas");
request.ClientCertificates.Add(certificate);
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(new Cookie("apicookie", "myCookieString") { Domain = "apidomain.com" });
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (var reader = new System.IO.StreamReader(response.GetResponseStream(), ASCIIEncoding.ASCII))
{
    result = reader.ReadToEnd();
}
return result;

The server returns a 400 error.

Upvotes: 0

Views: 1025

Answers (1)

Carles
Carles

Reputation: 453

(I don't have enough reputation to answer through a comment) Based on my experience using webrequest, some servers reject non-standard requests; I mean, first, you need to be sure that you set all headers properly for the http request (user-agent, referer, language, etc.).

Then, ensure that you use .NET framework 4.5 or higher, since older versions have problems managing some certificates.

Upvotes: 2

Related Questions