首页 > 解决方案 > .Net Core + Kubernetes > AuthenticationException:远程证书根据验证程序无效

问题描述

我正在研究托管在 Kubernetes 集群上的几个 Dotnet Core API,其中一些 API 确实调用了其他 API,这就是引发标题异常的时候。

我是否编辑 appsettings.json 并用 http 替换所有 https 并不重要——事实上,devops 团队的人建议我这样做——因为抛出了相同的异常。

这是我用于 http 调用的一小段代码:

int idCity = Convert.ToInt32(Utils.GetConfig().GetSection("Settings")["idCity"]);

using (HttpClient client = new HttpClient())
{
    client.BaseAddress = new Uri(Utils.GetConfig().GetSection("xxx")["xxxx"]);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    string queryString = "?startDate=" + startDate + "&endDate=" + endDate + "&idCity=" + idCity;

    HttpResponseMessage response = client.GetAsync(queryString).GetAwaiter().GetResult();

    if (response.IsSuccessStatusCode)
    {
        var resultHolidays = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
        return JsonConvert.DeserializeObject<JSONGeneric<HolidayDTO>>(resultHolidays);
    }
    else
    {
        return null;
    }
}

我有一份 .crt 格式的证书副本,并且还尝试过:

string certPath = Path.Combine(_env.ContentRootPath, _configuration.GetSection("Certificate")["certificatePath"]);
string pwd = _configuration.GetSection("Certificate")["certificatePwd"];

HttpClientHandler requestHandler = new HttpClientHandler();
requestHandler.ClientCertificates.Add(new X509Certificate2(certPath, pwd,
    X509KeyStorageFlags.MachineKeySet));

using (HttpClient client = new HttpClient(requestHandler))
{
    ...
}

无济于事,因为抛出了相同的异常。

我不是使用证书的专家,但我确实需要让它工作,以便能够在 pod 中调用其他 api 中的 api,所以任何帮助将不胜感激。

更新 1:“奇怪”的事情是,如果我只是复制要请求的 url——无论你使用 http 还是 https——并将其粘贴到安装了证书的浏览器中,它确实可以工作。如果您在浏览器中复制并粘贴 url 的 http 版本,Kubernettes(或任何人)会重定向到 https 版本,但最终您会得到结果。不是来自.Net

标签: c#ssl.net-corecertificatessl-certificate

解决方案


我会首先在客户端禁用证书验证,然后看看行为是什么。你可以这样做:

var httpHandler = new HttpClientHandler {
    ServerCertificateCustomValidationCallback = (m, crt, chn, e) => true
};

using var httpClient = new HttpClient(httpHandler);
// rest of the code 

如果调用成功,下一步是调整证书验证回调以检查服务器的证书。

注意:在您的示例中,您正在配置客户端证书,如果您托管服务并希望根据其证书授权您的客户端,这很有用,如此处所述。从问题描述中,我了解到您需要的是相反的:验证客户端中的服务器证书。

var srvCrt = new X509Certificate2(certPath, pwd);

var httpHandler = new HttpClientHandler {
    ServerCertificateCustomValidationCallback = (m, crt, chn, e) => {
        return crt.Thumbprint == srvCrt.Thumbprint;
    }
};

using var httpClient = new HttpClient(httpHandler);
// rest of the code

推荐阅读