0

In WCF or web services we add details of certificate in client credential tag as below:

<clientCredentials>
    <clientCertificate storeLocation="LocalMachine" x509FindType="FindBySubjectName" storeName="My" findValue="XYZ" />
</clientCredentials>

But how can we configure it in Rest Client Case where we just need to access a URI of RestFul service.?

Alex
  • 37,502
  • 51
  • 204
  • 332
Techie
  • 15
  • 5

1 Answers1

0

You can add a client certificate to a web request like this.

X509Store store = new X509Store("My", StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);

X509Certificate2Collection certificates = store.Certificates.Find(X509FindType.FindBySubjectKeyIdentifier, "XYZ", true);
X509Certificate2 certificate = certificates[0];

HttpWebRequest request = new HttpWebRequest();
request.ClientCertificates.Add(certificate); 

Note: WebRequestis obsolete.

Try using HttpClient instead, which would look something like this

X509Store store = new X509Store("My", StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);

X509Certificate2Collection certificates = store.Certificates.Find(X509FindType.FindBySubjectKeyIdentifier, "XYZ", true);
X509Certificate2 certificate = certificates[0];

WebRequestHandler handler = new WebRequestHandler();
handler.ClientCertificates.Add(certificate);
HttpClient client = new HttpClient(handler);
Alex
  • 37,502
  • 51
  • 204
  • 332
  • but is there a way to read the certificate details like store name , Location , value etc from web.config ? I have to make the details configurable – Techie Dec 06 '16 at 10:13
  • yes, just pass them in using ConfigurationManager, or however you read your configuration file – Alex Dec 06 '16 at 10:13
  • Thanks @Alex I was able to pass in store name and find value of a certificate but unable to configure it for find type and store location – Techie Dec 06 '16 at 10:50
  • store them as appSettings in your config file, then use ConfigurationManager.AppSettings – Alex Dec 06 '16 at 10:52
  • yes but can not pass the string values in X509Store constructor we can only pass a StoreLocation enum – Techie Dec 06 '16 at 10:57
  • So use Enum.Parse?! – Alex Dec 06 '16 at 11:01
  • Thanks @Alex yes that way we can but was searching if there is another way for that as we do for WCF . anyways I will continue with this way – Techie Dec 06 '16 at 11:58
  • WCF is very different to web requests. – Alex Dec 06 '16 at 11:59
  • If this answer was helpful please up vote and mark as an answer – Alex Dec 06 '16 at 11:59