在.NET Core中的Web请求中使用NTLM身份验证

时间:2018-12-10 05:23:07

标签: c# .net-core ntlm

更新 原来我要做的就是升级到.NET Core 2.1!谢谢大家的解决方案!


我有一个.NET Core 2.0控制台应用程序,需要向使用Windows身份验证(特别是NTLM)的API发出Web请求。这是我公司的内部API,我很难尝试成功连接到它,并不断获得401。

我的研究

我签出了SO:

然后,我发现了.NET Core github中提出的问题,它说it has been resolved。我尝试关注a code example there,但仍然无法正常工作。

我的代码

到目前为止,这是我所拥有的,我更改了公司网络上托管的Uri,但我希望这足以在本地运行。

public class NTLMProxy
{
    private readonly HttpClient _httpClient;

    public NTLMProxy()
    {
        _httpClient = CreateHttpClientWithNTLM();
    }

    public Task<HttpResponseMessage> GetUsers()
    {
        var httpRequest = new HttpRequestMessage(HttpMethod.Get, _httpClient.BaseAddress);

        return _httpClient.SendAsync(httpRequest);
    }

    public HttpClient CreateHttpClientWithNTLM()
    {
        var uri = new Uri("http://ntlmservice.com/services/api/foo");
        var credentialsCache = new CredentialCache { { uri, "NTLM", CredentialCache.DefaultNetworkCredentials } };
        var handler = new HttpClientHandler { Credentials = credentialsCache };
        var httpClient = new HttpClient(handler) { BaseAddress = uri };
        httpClient.DefaultRequestHeaders.ConnectionClose = false;
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        ServicePointManager.FindServicePoint(uri).ConnectionLeaseTimeout = 120 * 1000;  // Close connection after two minutes

        return httpClient;
    }
}

如果您有任何想法/建议,请告诉我。

1 个答案:

答案 0 :(得分:0)

对于.NET Core 2.1,我可以使用HttpClientFactory

来实现此实现

ConfigureServices(IServiceCollection services)的{​​{1}}中,我将其命名为class Startup注册:

HttpClient

在需要 services.AddHttpClient("myName").ConfigurePrimaryHttpMessageHandler(_ => new HttpClientHandler { Credentials = new CredentialCache { { new Uri("url"), "NTLM", new NetworkCredential("username", "password", "domain") } } }); 的位置,只需像这样解决它:

HttpClient

别忘了将工厂注入构造函数中。

var client  = _httpClientFactory.CreateClient("myName"); 

祝你好运!