.Net Core + Kubernettes > AuthenticationException: 根据验证程序,远程证书无效

.Net Core + Kubernettes > AuthenticationException: The remote certificate is invalid according to the validation procedure

我正在处理托管在 Kubernettes 集群上的几个 Dotnet Core API,其中一些 API 会调用其他 API,这就是标题中的异常被抛出的时候。

我是否编辑 appsettings.json 并将所有 https 替换为 http 并不重要 - 事实上,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))
{
    ...
}

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

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

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

我将从在客户端中禁用证书验证开始,然后查看行为是什么。你可以这样做:

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

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

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

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

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