0

I have an issue - my http request to TFS always returns "401" status code.

Request code below:

public async Task TfsPostRequest(string url, string body, string username, string password)
{
    using (var client = _httpClient.CreateClient("TfsClient"))
    {
        try
        {
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
            var content = new StringContent(body);
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            request.Content = content;
            

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

            request.Headers.Authorization = new AuthenticationHeaderValue("Ntlm", Base64Encode(username, password));

            var response = await client.SendAsync(request);
            response.EnsureSuccessStatusCode();
        }
        catch (HttpRequestException ex)
        {
            ...
        }
        catch (JsonException ex)
        {
            ...
        }
        catch (Exception ex)
        {
            ...
        }
    }
}

Base64Encode method:

public string Base64Encode(string username, string password)
{
    string creds = string.Format("{0}:{1}", username, password);
    byte[] bytes = Encoding.Unicode.GetBytes(creds);
    return Convert.ToBase64String(bytes);
}

HttpClient configuration code:

builder.Services.AddHttpClient("TfsClient", client => {
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
    client.DefaultRequestHeaders.Connection.Add("keep-alive");
});

When i try to execute simular one request using

credentialCache.Add(new Uri(uri), "Ntlm", validatingNetworkCredential);

with HttpWebRequest it works correct.

My code will be executing with different user credentials and i want to use http client for that task instead of HttpWebRequest. Is it possible?

3
  • 1
    A simple base64 encoding of the user name and password to be sent as auth header - that is not sufficient for NTLM authentication. The NTLM authentication involves back and forth type 1 , type 3 header values between client and webserver, it is not as simple as you seem to try out. Commented Feb 16, 2023 at 12:41
  • You could try this approach explained in this article, blog.thenetw.org/2021/02/04/… . It sends the network credentials to the HttpClientHandler. Commented Feb 16, 2023 at 12:44
  • FYI - If you are hosting in IIS on Windows, you may have to change the authentication settings in IIS to NTLM.
    – thewallrus
    Commented Feb 16, 2023 at 13:00

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.