How do I add authentication headers to HttpClient (C#) requests?

To add authentication headers to HttpClient requests in C#, you typically set the Authorization header with the appropriate value. Most commonly, this involves setting a bearer token for OAuth or a basic authentication header. Below I'll show an example of how you can do both.

Bearer Token Authentication

When using bearer token authentication, you need to obtain the token from the authentication provider and then add it to the Authorization header as a Bearer token.

Here's how you can do it:

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        using (var client = new HttpClient())
        {
            // Replace YOUR_TOKEN with your actual bearer token
            string bearerToken = "YOUR_TOKEN";

            // Add an Authorization header with the Bearer token
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", bearerToken);

            // Your API endpoint
            string url = "https://api.example.com/data";

            // Send a GET request
            HttpResponseMessage response = await client.GetAsync(url);

            if (response.IsSuccessStatusCode)
            {
                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseBody);
            }
            else
            {
                Console.WriteLine("Error: " + response.StatusCode);
            }
        }
    }
}

Basic Authentication

With basic authentication, you need to provide a username and password, which are combined into a string "username:password", base64-encoded, and then added to the Authorization header.

Here's how to add a basic authentication header:

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        using (var client = new HttpClient())
        {
            // Replace YOUR_USERNAME and YOUR_PASSWORD with your credentials
            string username = "YOUR_USERNAME";
            string password = "YOUR_PASSWORD";

            // Encode your credentials
            string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{username}:{password}"));

            // Add an Authorization header with the Basic scheme
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", credentials);

            // Your API endpoint
            string url = "https://api.example.com/data";

            // Send a GET request
            HttpResponseMessage response = await client.GetAsync(url);

            if (response.IsSuccessStatusCode)
            {
                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseBody);
            }
            else
            {
                Console.WriteLine("Error: " + response.StatusCode);
            }
        }
    }
}

Notes

  • Ensure that your authentication tokens and credentials are stored and transmitted securely.
  • Always dispose of HttpClient instances properly to free up resources. One common approach is to use a single HttpClient instance for the lifetime of the application (as shown in the examples) or manage its lifecycle properly if multiple instances are necessary.
  • Handle exceptions that might occur during the request, such as HttpRequestException.
  • When using HttpClient, it's often recommended to make it a singleton or reuse instances to avoid socket exhaustion.

By setting the Authorization header correctly, you can authenticate your HTTP requests sent from your C# application using HttpClient.

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon