HttpClient 对 Auvik Web API 的调用返回未经授权的

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

我正在使用以下代码访问我们网络上设备的 Auvik Web API。我使用的凭据在 Postman 中运行良好,响应为 200 Ok。当我在 C# 代码中使用相同的凭据时,我收到 401 Unauthorized。我尝试使用 WireShark 来查看请求,它们看起来几乎相同(需要不同的标头,如 Postman-Token)。

protected async Task<HttpClient> GetHttpClientAsync(int timeout)
{
    var name = await _Secrets.GetSecretAsync(_CK_API_USER);//_Secrets is a protected IReadOnlySecretService (custom code) to retrieve secret values
    var token = await _Secrets.GetSecretAsync(_CK_API_KEY);

    if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(token))
    {
        throw new ArgumentException($"The secret service must contain valid secret values for the following keys: [{_CK_API_USER}], [{_CK_API_KEY}].");
    }

    var client = new HttpClient { BaseAddress = new Uri(_BaseUrl), Timeout = TimeSpan.FromSeconds(timeout) };

    client.DefaultRequestHeaders.CacheControl = new CacheControlHeaderValue() { NoCache = true };
    client.DefaultRequestHeaders.Authorization = new BasicAuthenticationHeaderValue(name, token);
    client.DefaultRequestHeaders.Accept.Clear();

    return client;
}

我现在不太确定该怎么做。被屏蔽的部分是相同的,所以一切都告诉我请求应该产生相同的结果,但我们在这里。有什么建议吗?

对于其他上下文,我提供了 Postman 调用和使用 Postman 生成的 C# 代码(也返回 Unauthorized)的 C# 调用的屏幕截图:

成功:

失败:

c# http .net-core http-headers
1个回答
0
投票
var authenticationCredentials = $"{name}:{password}"; -- your token
var base64EncodedAuthenticationCredentials  = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(authenticationCredentials ));


requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Basic", base64EncodedAuthenticationCredentials );
var response = await client.SendAsync(requestMessage);

这是基本授权请求的标准类型。检查您的凭据值。

© www.soinside.com 2019 - 2024. All rights reserved.