HttpWebRequest and client certs?

  • Thread starter Thread starter EMonaco
  • Start date Start date
E

EMonaco

Is there any way to programmatically select a particular client certificate
and associate it with an HttpWebRequest instance? I know using WinINet this
was possible.


Erin.
 
Erin,

Sure.

System.Security.Cryptography.X509Certificates.X509Certificate cert =

System.Security.Cryptography.X509Certificates.X509Certificate.CreateFromCert
File(@certPath);


ServicePointManager.CertificatePolicy = new CertPolicy();


HttpWebRequest tuReq = (HttpWebRequest)WebRequest.Create(addr + "?" + TU);


tuReq.ClientCertificates.Add(cert);

tuReq.ContentType = "application/x-www-form-urlencoded";

tuReq.Method = "GET";

Make sure you have a class (either your class or another) that implements
ICertificatePolicy or your app will hang because of the untrusted cert
issue.

EX:



class CertPolicy: ICertificatePolicy

{

public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate
certificate,

WebRequest request, int certificateProblem)

{

return true;

}



}

Alex
 
Trebek,

Thanks, was able to dig up an ASP.NET example code and came up with

httpreq = (HttpWebRequest) HttpWebRequest.Create(this.tbURL.Text);

httpreq.Method = sMethod;


// Has a client certificate file been given?

if(this.tbCERTPATH.Text.Length>0)

{

try

{

httpreq.ClientCertificates.Add(System.Security.Cryptography.X509Certificates
..X509Certificate.CreateFromCertFile(this.tbCERTPATH.Text));

}

catch(System.Exception pe)

{

System.Diagnostics.Debug.WriteLine(pe.ToString());

}

}

I assume I need an implemented ICertificatePolicy if the server certificate
is not trusted on the given client?



Erin.
 
Yes, even if the client IS trusted, I suggest doing it because the in the
early releases (Beta and maybe 1.0 - can't remember), this was buggy and
never really worked as intended.

Alex
 
Back
Top