Creating a .NET Client for Basic Authentication in Web APIs

Introduction

In my previous blog post, I demonstrated how to implement basic authentication in a web API using ASP.NET. In this blog post, we will delve into creating a .NET client that utilizes basic authentication to authenticate against the server.

While the previous blog post focused on testing the API with Postman, this time we’ll explore accessing authenticated web services or APIs from a C# client application.

Setting Up the Client for Basic Authentication

To begin, let’s create a new console application named “BasicAuthTest” in .NET 7. Once the application is set up, we’ll define the URL for the server, which in this case is “localhost:7264”.

Additionally, we’ll specify the username as “John” and the password as “password”, just like we did in the previous implementation.

Creating the HTTP Client for Basic Authentication

Now, let’s create an HTTP client and set its base address to the specified URL. This client will be used to communicate with the authenticated web API.

To add the authentication header, we’ll set the default request headers of the client. We’ll create a new AuthenticationHeaderValue with the scheme “basic” and the value as the base64-encoded username and password.

Remember, both the username and password should be base64-encoded strings.

using System.Text;

var url = "https://localhost:7264";
var username = "john";
var password = "password";

var client = new HttpClient();
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Authorization
    = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", 
        Convert.ToBase64String(Encoding.ASCII.GetBytes($"{username}:{password}")));

Sending the Request

With the client and authentication set up, we can proceed to send the request to the server. We’ll make a GET request to the “/weatherforecast” path, as that is the endpoint we previously defined in the web API.

After sending the request, we’ll check if the response status code indicates success. If it does, we’ll retrieve the response content as a string and print it. Otherwise, we’ll output the response status code to identify any authentication failures.

var response = await client.GetAsync("/WeatherForecast");
if(response.IsSuccessStatusCode)
{
    var content = await response.Content.ReadAsStringAsync();
    Console.WriteLine(content);
}
else
{
    Console.WriteLine(response.StatusCode.ToString());
}

Testing the Client for Basic Authentication

Let’s run the application and observe the results. By debugging through the code, we can ensure that the client is properly configured and that the authentication header is correctly added to the requests.

In successful scenarios, we should receive the expected response, such as the weather forecast data. Conversely, if there are authentication issues, the response status code will indicate an unauthorized access attempt.

Conclusion

In conclusion, we have successfully created a .NET client to interact with a web API authenticated using basic authentication. We learned how to set up the client, add the necessary authentication header, and handle the response accordingly.

This straightforward implementation allows us to securely access authenticated web services or APIs from a C# client application.

If you found this blog post helpful, please show your support by liking the video and subscribing to our channel. We appreciate your continued engagement and hope to bring you more valuable content in the future. Thank you for reading!

A YouTube video of this implementation is available here.