簡體   English   中英

.Net Core + Kubernetes > AuthenticationException:遠程證書根據驗證程序無效

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

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

無濟於事,因為拋出了相同的異常。

我不是使用證書的專家,但我真的需要讓它發揮作用,以便能夠在 api 的 pod 調用其他 api 中制作,所以任何幫助將不勝感激。

更新 1:“奇怪”的事情是,如果我只是復制要請求的 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 

如果調用成功,下一步是調整證書驗證回調以檢查服務器的證書。

注意:在您的示例中,您正在配置客戶端證書,如果您托管服務並希望根據其證書授權您的客戶端,這很有用,如此所述。 從問題描述中,我了解到您需要的是相反的:驗證客戶端中的服務器證書。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM