Understanding API Authentication in C# : Mastering
Source: Dev.to
Basic Authentication (Username & Password)
Basic authentication sends the username and password encoded in Base64. It is simple to implement but should only be used over HTTPS and is generally suited for internal or test APIs.
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
// Create the client
var client = new HttpClient();
// Encode credentials
var byteArray = Encoding.ASCII.GetBytes("username:password");
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
// Send request
var response = await client.GetAsync("https://api.example.com/data");
Bearer Token Authentication (JWT)
Bearer tokens (e.g., JWTs) are stateless and scalable, making them ideal for modern REST APIs.
using System.Net.Http;
using System.Net.Http.Headers;
// Create the client
var client = new HttpClient();
// Add the JWT as a Bearer token
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", "your_jwt_token_here");
// Send request
var response = await client.GetAsync("https://api.example.com/userinfo");
OAuth Bearer Token
OAuth providers (Google, GitHub, Facebook, etc.) issue access tokens that are sent as Bearer tokens. This approach is widely used for third‑party integrations.
using System.Net.Http;
using System.Net.Http.Headers;
// Create the client
var client = new HttpClient();
// Use the OAuth access token
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", "access_token_from_oauth");
// Send request
var response = await client.GetAsync("https://api.github.com/user");
HMAC Signature Authentication
HMAC signatures use a shared secret to hash request data, ensuring both authenticity and integrity. This method is well‑suited for secure system‑to‑system communication.
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
// Shared secret
var key = "secretkey";
var message = "GET:/api/data";
// Compute HMAC SHA256 signature
using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key));
var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(message)));
// Create the client
var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-Signature", signature);
// Send request
var response = await client.GetAsync("https://api.example.com/data");
Security Considerations
- Always use HTTPS when transmitting credentials or tokens.
- Never store plain‑text passwords; prefer token‑based schemes for production.
- Rotate secrets and tokens regularly to reduce exposure risk.
- Validate signatures on the server side when using HMAC to ensure request integrity.