Rest API web.config C# 中的客户端配置

Rest API Client configuration in web.config C#

我需要在其余 API 客户端中使用 Https 相互身份验证,因为我们只能获取 URI,因此我们无法像为 WCF 那样添加客户端证书。 所以我在我的 web .config 中添加了密钥,如下所示:

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

我正在我的客户端代码中使用它,如下所示:

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

这是在 REST API 客户端中实现相互身份验证的正确方法吗?

或者,如果不能,有人可以帮助我找到正确的方法吗?

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)

这有时也称为双向 SSL 身份验证。

您正在做的事情显示了实现此目标的正确意图,因为:

  1. 您在创建请求时添加客户端证书
  2. 您使用 HTTPS 与服务器通信

我唯一的建议是(如果这是一个严格的要求)通过以下方式强制执行此过程:

  1. 如果未找到客户端证书,请确保不发出请求
  2. 提供一个 ServerCertificateValidationCallback 方法,您可以在验证服务器证书时添加自定义验证(或强制策略)
  3. 使用 X509Certificate2X509Certificate2Collection 类 代替 (see here why)