api - 如何使用 AutoRest 客户端传递客户端证书

标签 api ssl x509certificate autorest

我们正在使用 AutoRest 基于 API Swagger 文件生成客户端代码。

我正在尝试将客户端证书传递给 API。但注意到生成的客户端代码不接受 WebRequestHandler。

生成的代码如下所示:

public MyTestApiV1(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
        {
            if (baseUri == null)
            {
                throw new ArgumentNullException("baseUri");
            }
            this.BaseUri = baseUri;
        }

我觉得我错过了一些东西。有人设法使用 AutoRest 发送客户端证书吗?

尝试过这个,但 webRequestHandler 始终为空:

var webRequestHandler = client.HttpMessageHandlers.First() as WebRequestHandler;
            if (webRequestHandler != null)
            {
                var secretRetrieved = keyVault.GetSecretAsync("my-cert");
                var pfxBytes = Convert.FromBase64String(secretRetrieved.Result);
                // or recreate the certificate directly
                var certificate = new X509Certificate2(pfxBytes);
                webRequestHandler.ClientCertificates.Add(certificate);
            }

最佳答案

您可以使用另一个重载构造函数:

/// <summary>
/// Initializes ServiceClient using base HttpClientHandler and list of handlers.
/// </summary>
/// <param name="rootHandler">Base HttpClientHandler.</param>
/// <param name="handlers">List of handlers from top to bottom (outer handler is the first in the list)</param>
protected ServiceClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers)

ServiceClient 是生成的客户端的基类。因此,代码可能如下所示:

var secretRetrieved = keyVault.GetSecretAsync("my-cert");
var pfxBytes = Convert.FromBase64String(secretRetrieved.Result);
// or recreate the certificate directly
var certificate = new X509Certificate2(pfxBytes);
WebRequestHandler webRequestHandler = new WebRequestHandler();
webRequestHandler.ClientCertificates.Add(certificate);
var client = new MyTestApiV1(webRequestHandler);
client.BaseUri = baseUri;

关于api - 如何使用 AutoRest 客户端传递客户端证书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43795845/

相关文章:

wcf - C# WCF 客户端错误 "The private key is not present in the X.509 certificate"

使用通配符证书的 WCF 服务给出了 DNS 身份错误

javascript - 在 javascript 中使用 last.fm API

php - API 图形统计 PHP HTML CSS

symfony - 如何告诉 Symfony2 不要使用 https?

c++ - 向现有 TCP 和 UDP 代码添加 SSL 支持?

node.js - 如何在 NodeJS 中解码 X.509 主题(来自客户端证书)

java - Api 21 上的工具栏项 MaterialButton 中的颜色错误

python - 通过 Python API 客户端发送到 BigQuery 时验证查询出现语法错误

apache - 我发现一个问题,当我将 apache benchmark(ab) 与 http 一起使用时