C# HttpClient - How to use basic authentication and set the HTTP authorization header

Basic authentication is becoming a rare sight, however it is still quite widely used due to its simplicity. In C#, using the HttpClient and HttpRequestMessage you can provide an Authorization header for a request. With basic authentication you provide the value "basic <base64EncodedUserAndPassword>" in the Authorization header for every request. The value of base64EncodedUserAndPassword is a username and password concatenated together with a colon in between. Such as: "Peter:Rasmussen" if my username was "Peter" and Password "Rasmussen", afterwards it is base64 encoded.

Below is an example of how to send a request with a basic authorization header:

using System.Net.Http.Headers;

var userName = "Peter";
var userPassword = "Rasmussen";

var authenticationString = $"{userName}:{userPassword}";
var base64String = Convert.ToBase64String(
   System.Text.Encoding.ASCII.GetBytes(authenticationString));

var requestMessage = new HttpRequestMessage(HttpMethod.Get, "/SomeApi/SomePath");
requestMessage.Headers.Authorization = 
   new AuthenticationHeaderValue("Basic", base64String);

var httpClient = new HttpClient();
httpClient.Send(requestMessage);

In the above we declare our username and password as variables. We then concatenate them with a colon : in between and Base64 encodes the string. We then create a HttpRequestMessagewith the target URL and our HTTP Verb (Get). On the requestMessage we add an Authorization header which we set to basic and give it the value of our base64 encoded string. All there is left is to create a HttpClient and send off the request!

That is it

I hope you found this helpful, feel free to leave a comment down below if you have any questions!