.Net Core + Kubernettes > 身份验证异常:根据验证过程,远程证书无效



我正在研究托管在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))
{
...
}

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

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

更新1:"奇怪"的是,如果我只是复制要请求的网址 - 无论您使用http还是https - 并将其粘贴到安装了证书的浏览器中,它确实可以工作。如果您将网址的http版本复制并粘贴到浏览器中,Kubernettes(或无论是谁(会重定向到https版本,但最终你会得到结果。不是来自 .NET

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

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

最新更新