问题
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:
- Use the
X509Certificate
class to read the cert from a .cer file. - 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);
来源:https://stackoverflow.com/questions/16847556/how-to-add-registry-certificate-to-httpwebrequest