【问题标题】:While trying to retrieve the AccesToken using HttpClient I am getting an error尝试使用 HttpClient 检索访问令牌时出现错误
【发布时间】:2023-03-05 05:34:01
【问题描述】:

尝试使用 HttpClient 从 Windows 服务器检索访问令牌时出现错误:

“GSSAPI 操作因错误而失败 - 提供了无效的状态代码(SPNEGO 找不到协商机制)。”

private readonly HttpClient client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true, AllowAutoRedirect = true }) { Timeout = TimeSpan.FromSeconds(5) };



public async Task<UserAccessToken> GetAuthenticationToken(string accessBrokerHost)
    {
        try
        {
            var response = await client.SendAsync(new HttpRequestMessage(HttpMethod.Get, $"{accessBrokerHost}/Token")).ConfigureAwait(false); 


//accessBrokerHost is HTTP SPN created internally in a windows server


            if (!response.IsSuccessStatusCode)
            {                    
                throw new BrokerNotAvailableException();
            }
            return await response.Content.ReadAsAsync<UserAccessToken>().ConfigureAwait(false);
        }            
    }

由于 GSSAPI 操作失败并出现错误而引发 system.ComponentModel.win32Exception - 提供了无效的状态代码(SPNEGO 找不到协商机制)

上面的代码在 Windows 中运行良好,但在 Linux 中却不行(我使用的是 Linux Mint)。据我所知,它指的是尝试使用 Kerberos 但没有激活 Kerberos 票证来对 Linux 进行身份验证的问题。

【问题讨论】:

  • 感谢@dustinos3 的编辑。我很感激。
  • 根据github.com/dotnet/corefx/issues/29941 看来这是一年前的错误,您使用的是什么版本?也许使用最新版本会为您解决问题。
  • 感谢israelss的回复,我正在使用netcoreapp2.2。我已经看到很多与此问题相关的内容,包括您建议的链接,但我不太明白。
  • 我可能不是 c# 方面的专家,但我很擅长谷歌搜索,哈哈,而且由于错误提到了 win32,它不是 linux 的一部分,我想这不正常,似乎有人当您不在 Windows 中时,通过阻止 SocketsHttpHandler 覆盖 HttpHandler 来解决相同的问题,此链接可以更好地解释它。 stackoverflow.com/questions/52266659/…
  • 感谢israelss,我已经尝试过了,但没有成功。得到同样的错误。

标签: c# .net linux .net-core dotnet-httpclient


【解决方案1】:

最后,我找到了这个问题的解决方案。

解决方案 1:

Step 1. 根据this,你应该添加

 AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", false);

第 2 步。由于 UseDefaultCredentials = true 在这里不起作用,您需要手动将网络凭据传递给 HttpClient,如下所示

HttpClient client = new HttpClient(new HttpClientHandler{Credentials = new NetworkCredential("UserName" "Password", "Domain")}

第 3 步。您应该将 HttpRequestMessage 版本更改为

HttpVersion.Version11.

解决方案 2:您也可以通过将整个应用程序转换为 NetcoreApp3.0

来解决此问题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-02
    • 2015-12-08
    • 1970-01-01
    • 2021-09-11
    • 2021-11-07
    • 2020-07-26
    • 2019-08-24
    相关资源
    最近更新 更多