How to add registry certificate to HttpWebRequest?

2020-06-29 06:22发布

问题:

My apologies in advance if this is a duplicate question. I am new to the 'lingo' of HttpWebRequest and my google searching turned up fruitless.

Some time ago I wrote a login controller that utilizes HttpWebRequest. It works fine when I run it at home. I tried the same login controller from behind my company's firewall and it is expecting a Client Authentication certificate to get through. I read online that the certificate lives in my desktop's system registry. Sure enough, I can open IE and internet options->content->certificates I can see in the dialog window the client certificate that IE is using to do the same thing I want to accomplish with my login controller.

Can someone please provide a C# code snippet showing a way add the client certificates from the registry to my HttpWebRequest?

for example,

var request = (HttpWebRequest) WebRequest.Create("https://www.someplace.com/Login");
                request.Credentials = CredentialCache.DefaultCredentials;
                request.ClientCertificates.Add(); //<---- ? how to add registry certs?
                request.KeepAlive = true;

etc.

回答1:

This MS knowledge base article covers what you need - How to send a client certificate by using the HttpWebRequest and HttpWebResponse classes.

As described in the article, you have two options open to you:

  1. Use the X509Certificate class to read the cert from a .cer file.
  2. Use CryptoAPI calls to extract the certificate information directly from the certificate store.

The second option is a nuisance, and needs elevated trust to extract from the cert. store. So you'll want to go for option 1 if possible. Something like this:

X509Certificate Cert = X509Certificate.CreateFromCertFile("C:\\mycert.cer");
HttpWebRequest Request = (HttpWebRequest)WebRequest
                         .Create("https://YourServer/sample.asp");
Request.ClientCertificates.Add(Cert);