通过 Azure Service Fabric 请求时,HttpClient 中基于证书的身份验证失败

Certificate based authentication in HttpClient failing when requested through Azure Service Fabric

我有一个服务结构应用程序,我正在尝试使用基于证书的身份验证调用 API。

WebRequestHandler handler = new WebRequestHandler();
//fetching certificate from key vault. The fetch url is identical in both the cases and thumbprint is same
X509Certificate certificate = GetCertificate();
handler.ClientCertificates.Add(certificate);

var baseUrl = "https://myUrl";
var requestUri = "request";
var content = "content";

using (HttpClient httpClient = new HttpClient(handler))
{
    httpClient.BaseAddress = new Uri(baseUrl);

    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUri)
    {
        Content = new StringContent(content, Encoding.UTF8, MediaTypeNames.Text.Plain)
    };

    HttpResponseMessage result;
    using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(100)))
    {
        try
        {
            result = httpClient.SendAsync(request, cts.Token).Result;

            //check the result here
        }
        catch (OperationCanceledException e) when (cts.IsCancellationRequested)
        {
            ...
        }
    }
}

当我在本地 运行 完全相同的代码时,它可以工作,而当我在 Azure 服务结构中 运行 它时,它失败了。下面是我在代码中检查的结果。

Service Fabric 本地集群:

StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: { Pragma: no-cache Cache-Control: no-cache Date: Sat, 06 Jun 2020 03:40:44 GMT Server: Microsoft-IIS/10.0 X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET Content-Length: 67 Content-Type: application/json; charset=utf-8 Expires: -1 }

Azure 中的 Service Fabric 集群:

StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: { Pragma: no-cache Cache-Control: no-cache Date: Sat, 06 Jun 2020 03:30:33 GMT Server: Microsoft-IIS/10.0 WWW-Authenticate: Bearer X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET Content-Length: 61 Content-Type: application/json; charset=utf-8 Expires: -1 }

我检查了 WWW-Authenticate header 是身份验证服务器接受。我知道它接受基于证书的身份验证并且在本地工作。为什么它拒绝授权并发回 WWW-Authenticate: Bearer header 当我 运行 它在云端时?

我发现证书需要有私钥才能授权,而我使用的密钥库证书没有私钥。

这有点令人困惑,因为 certificate.HasPrivateKey 在我的机器和 Azure 环境中都是错误的。它在我的机器上运行的原因是我的机器上安装了证书。

我通过从我的存储中删除证书进行测试,并通过使用具有私钥的证书更新密钥库来解决它。