Been elaborating a bit with HttpClient for building a rest client. But I can\'t figure out, nor find any examples on how to authenticate towards the server. Most likely I wi
As of .NET 4.8, .NET core 3.1 and .NET Standard 2.0 they recommend using both HttpClient
and CredentialCache
. Something like this:
const string basicAuthUser = @"myUser";
const string basicAuthPass = @"myPass";
const string host = @"https://my.host.com";
const string path = @"/api";
using (var httpClientHandler = new HttpClientHandler()) {
httpClientHandler.PreAuthenticate = true;
httpClientHandler.UseDefaultCredentials = true;
var basicCredCache = new CredentialCache();
var basicCredentials = new NetworkCredential(basicAuthUser, basicAuthPass);
basicCredCache.Add(new Uri(new Uri(host), path), "Basic", basicCredentials);
httpClientHandler.Credentials = basicCredCache;
using (var client = new HttpClient(httpClientHandler)) {
client.BaseAddress = new Uri(host);
using (var request = new HttpRequestMessage(HttpMethod.Get /*HttpMethod.Post*/, path)) {
//
// Send request here
//
}
}
}
EDIT: Note that wrapping HttpClient
into using
may lead to Socket exhaustion under high load. However keeping HttpClient
as singleton may lead to other problems such as stale DNS issue. Start reading this long story from here.
I tried Duncan's suggestion, but it didn't work in my case. I suspect it was because the server I was integrating with, didn't send a challenge or ask for authentication. It just refused my requests, because I didn't supply an Authorization header.
So I instead did the following:
using (var client = new HttpClient())
{
var encoding = new ASCIIEncoding();
var authHeader = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(encoding.GetBytes(string.Format("{0}:{1}", "username", "password"))));
client.DefaultRequestHeaders.Authorization = authHeader;
// Now, the Authorization header will be sent along with every request, containing the username and password.
}
Notice that the example here only works with Basic authentication.