How to add registry certificate to HttpWebRequest?

隐身守侯 提交于 2019-12-05 06:20:12

问题


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);


来源:https://stackoverflow.com/questions/16847556/how-to-add-registry-certificate-to-httpwebrequest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!