Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpClient and Basic Auth in URL

I'd like to use HttpClient and HTTP basic auth by specifying username and password in the URL, like this:

var request = new HttpRequestMessage(HttpMethod.Get, 
    "https://username:[email protected]");

using (var client = new HttpClient()) {
    await client.SendAsync(request);
}

However there is no Authorization header sent with the request.

Is there a way to tell HttpClient to support this, or do I have to manually fetch the credentials from the URL and set the headers myself?

like image 288
Boxiom Avatar asked Mar 05 '18 08:03

Boxiom


1 Answers

You need to set the header instead of passing it through the URL

var byteArray = Encoding.ASCII.GetBytes("username:password1234");
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
like image 121
Jamie Rees Avatar answered Nov 15 '22 08:11

Jamie Rees