简体   繁体   中英

Rest API Client configuration in web.config C#

I need to use Https mutual authentication in a rest API client since we only get the URI we can not add client certificate as we do for WCF. So I have added keys in my web .config as below :

<appSettings>
    <add key="URI" value="https://localhost:8080/RestfulAPI/RestfulService.svc/restfulData" />
    <add key="CertificateValue" value="certficatename"/>
    <add key="CertificateLocation" value="LocalMachine"/>
    <add key="CertificateStoreName" value="My"/>
    <add key="CertificateFindType" value="FindBySubjectName"/>
</appSettings>

and I am using it in my client code as below:

X509Store store = new X509Store(ConfigurationManager.AppSettings["CertificateStoreName"], ConfigurationManager.AppSettings["CertificateLocation"]);
            store.Open(OpenFlags.ReadOnly);
            X509CertificateCollection certificates = store.Certificates.Find(ConfigurationManager.AppSettings["CertificateFindType"], ConfigurationManager.AppSettings["CertificateValue"], true);
            X509Certificate certificate = certificates[0];
            HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
            request.ClientCertificates.Add(certificate);

HttpWebResponse response = request.GetResponse() as HttpWebResponse

Is this the right way to implement mutual authentication in REST API client ?

Or if not can someone please help me with the correct approach?

Mutual Authentication is a security feature in which a client process must prove its identity to a server, and the server must prove its identity to the client, before any application traffic is sent over the client-to-server connection.

( source )

This is also called sometimes a 2-way SSL authentication.

What you're doing shows the right intent for achieving this because:

  1. You add the client certificate when creating the request
  2. You use HTTPS to communicate with the server

My only suggestion is (if this is a strict requirment) to enforce this process by:

  1. Make sure the request is not made if a client ceritificate is not found
  2. Provide a ServerCertificateValidationCallback method where you can add custom validaton (or enforcment policies) when validating the server certificate
  3. Use X509Certificate2 and X509Certificate2Collection classes instead ( see here why )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM