C#
WebRequest
authentication
HTTP headers
programming

How to add basic authentication header to WebRequest

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

To add HTTP Basic authentication to a request in C#, you build the username:password string, encode it as Base64, and place it in the Authorization header. That process is simple, but it only makes sense over HTTPS because Basic authentication is an encoding scheme, not encryption.

Add the Header to WebRequest

If you are maintaining older code that still uses WebRequest or HttpWebRequest, the header looks like this:

csharp
1using System;
2using System.IO;
3using System.Net;
4using System.Text;
5
6string username = "api-user";
7string password = "secret";
8string credentials = Convert.ToBase64String(
9    Encoding.ASCII.GetBytes($"{username}:{password}")
10);
11
12HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://example.com/api/data");
13request.Method = "GET";
14request.Headers["Authorization"] = $"Basic {credentials}";
15
16using HttpWebResponse response = (HttpWebResponse)request.GetResponse();
17using StreamReader reader = new StreamReader(response.GetResponseStream());
18Console.WriteLine(reader.ReadToEnd());

That is the full mechanism. The server receives a header like:

text
Authorization: Basic base64-encoded-value

Why ASCII or UTF-8 Matters

The Basic authentication format is a byte sequence derived from username:password. Most examples use ASCII because many credentials are plain ASCII text. If your usernames or passwords may contain broader characters, make a deliberate encoding choice rather than copying examples blindly.

What matters most is that the client and server interpret the bytes the same way.

Prefer HttpClient in Newer Code

Even if you can add the header to WebRequest, new code is usually clearer with HttpClient.

csharp
1using System;
2using System.Net.Http;
3using System.Net.Http.Headers;
4using System.Text;
5using System.Threading.Tasks;
6
7static async Task Main()
8{
9    using var client = new HttpClient();
10
11    string raw = "api-user:secret";
12    string encoded = Convert.ToBase64String(Encoding.ASCII.GetBytes(raw));
13    client.DefaultRequestHeaders.Authorization =
14        new AuthenticationHeaderValue("Basic", encoded);
15
16    string response = await client.GetStringAsync("https://example.com/api/data");
17    Console.WriteLine(response);
18}

This version is easier to compose with modern async code and is generally a better direction if you are not forced to stay with legacy APIs.

Alternative: Use NetworkCredential

Some codebases prefer to assign credentials directly:

csharp
request.Credentials = new NetworkCredential("api-user", "secret");

Whether this results in the exact Basic header behavior you expect can depend on the server challenge flow and request configuration. If you specifically need an explicit Authorization header on the first request, setting the header yourself is usually less ambiguous.

Security Considerations

Basic authentication should be treated as sensitive even though the code is short.

  • always send it only over HTTPS
  • do not hard-code secrets into source files
  • prefer secrets from configuration or a secret store
  • consider token-based auth if the API supports it

The risk is not the header syntax. The risk is exposing credentials through insecure transport or poor secret handling.

Verify What the Server Expects

Some APIs accept Basic authentication only after an authentication challenge, while others expect the header on the very first request. That distinction explains why two examples that look similar can behave differently against different servers.

When debugging, inspect the outgoing request with a proxy or server logs rather than assuming the credential header was sent exactly as intended. The header format is easy; aligning with server behavior is the real integration task.

Common Pitfalls

  • Using Basic authentication over plain HTTP. Base64 is reversible and does not protect the credential.
  • Forgetting the Basic prefix before the encoded value in the header.
  • Assuming NetworkCredential always sends the header exactly when you want without verifying the server flow.
  • Hard-coding usernames and passwords directly in source code.
  • Sticking with WebRequest for new code when HttpClient would be a cleaner fit.

Summary

  • Basic auth in C# is just username:password encoded as Base64 and sent in the Authorization header.
  • The manual header approach works with legacy WebRequest code.
  • 'HttpClient is usually a better choice for new applications.'
  • Use HTTPS or do not use Basic authentication at all.
  • Keep credentials out of source and configuration checked into version control.

Course illustration
Course illustration

All Rights Reserved.