如何从代码调用 REST API,我只得到 AuthenticationException、UntrustedRoot

问题描述 投票:0回答:1

我对 REST 服务相当陌生,我正在尝试从同事那里调用 REST 服务,仅通过用户名和密码进行保护。

使用 Postman 一切都很好,我有一个 GET 到 URL,我选择“基本身份验证”,设置用户名和密码并获得预期结果。

现在我通过代码尝试了: 在没有用户/密码的情况下,每个代码调用其他网络服务工作得很好,但在这里我只是得到一个异常:

public async Task<List<string>> MinimalProblemShowcase()
{
    string authenticationString = $"{clientId}:{clientSecret}"; // no typo, values are copy/pasted
    string base64EncodedAuthenticationString = Convert.ToBase64String(Encoding.UTF8.GetBytes(authenticationString));
    _client.DefaultRequestHeaders.Add("Authorization", "Basic " + base64EncodedAuthenticationString);

    try
    {
        var httpResponse = _client.GetAsync(Url).Result;

        // ToDo: evaluate httpResponse - but we don't get here...
    }
    catch (Exception ex)
    {
        // ...instead we drop here:
        // System.Net.Http.HttpRequestException: 
        // The SSL connection could not be established, see inner exception.
        // --->System.Security.Authentication.AuthenticationException: 
        // The remote certificate is invalid because of errors in the certificate chain: UntrustedRoot
    }

    return [];
}

正如所指出的,我明白了

System.Net.Http.HttpRequestException: 
The SSL connection could not be established, see inner exception. 
---> System.Security.Authentication.AuthenticationException: 
    The remote certificate is invalid because of errors in the certificate chain: UntrustedRoot

我不知道明确使用证书,但如果是这样,它就在同一台机器上......

我怀疑,这只是我遗漏的一个小细节,但是什么......? 感谢您的任何提示或帮助!

.net rest asp.net-core authentication
1个回答
0
投票

您可以通过配置httpclient来忽略证书不受信任的问题

var httpClientHandler = new HttpClientHandler();
httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, sslPolicyErrors) =>{return true;};
builder.Services.AddScoped(sp => new HttpClient(httpClientHandler));

或者您可以使用您正在使用的证书进行一些验证。

httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, sslPolicyErrors) => {
    if (cert.GetCertHashString() == "A7E2BA992F4F2BE220559B8A5371F05A00A6E750") //FingerPrint of the certificate
    {
        return true;
    }
    return false;
};
© www.soinside.com 2019 - 2024. All rights reserved.