Friday, December 31, 2021

Configure HttpClient to consume windows authenticated NTLM service in ASP.NET Core

Recently I migrated a system to Linux based docker platform from IIS environment. I had a service call to some other API that has NTLM authentication.

That was working fine by just setting Credentials to HttpClient when hosted in IIS. 

But when you run dotnet app in Linux you do not have that windows authentication fancy feature. 

Below is how I managed to configure HttpClient with NTLM Authentication using CredentialCache.


public void ConfigureServices(IServiceCollection services)
{
services.AddCognitoIdentity();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
//// configure httpclient and consume this using HttpClientFactory
services.AddHttpClient("MyCompanyApiClient", c =>
{
c.BaseAddress = new Uri("https://mycompany/api/");
c.DefaultRequestHeaders.Add("Accept", "application/json");
}).ConfigurePrimaryHttpMessageHandler(() =>
{
return new HttpClientHandler()
{
//// this is how you set ntlm auth
Credentials = new CredentialCache
{
{ new Uri("https://mycompany/api/"), "NTLM", new NetworkCredential("username", "password") }
},
//// if there is a proxy
Proxy = new WebProxy ("http://companyproxy:8989")
};
}) ;
}
view raw ntlmAuth.cs hosted with ❤ by GitHub

No comments:

Post a Comment