DEV Community

Deepangshi S.
Deepangshi S.

Posted on

Understanding API Authentication in C# : Mastering

An authentication ensures that requests come from trusted users or systems.
Here’s a quick look at some common authentication methods:-

i.) Basic Authentication
var client = new HttpClient();
var byteArray = Encoding.ASCII.GetBytes("username:password");
client.DefaultRequestHeaders.Authorization = 
    new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

var response = await client.GetAsync("https://api.example.com/data");

Enter fullscreen mode Exit fullscreen mode

The simplest form username and password encoded in Base64. Best for internal or test APIs, not secure for public use without HTTPS.

ii.) Token-Based (JWT) Authentication
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = 
    new AuthenticationHeaderValue("Bearer", "your_jwt_token_here");

var response = await client.GetAsync("https://api.example.com/userinfo");

Enter fullscreen mode Exit fullscreen mode

Stateless and scalable, perfect for modern REST APIs.

iii.) OAuth 2.0
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = 
    new AuthenticationHeaderValue("Bearer", "access_token_from_oauth");

var response = await client.GetAsync("https://api.github.com/user");

Enter fullscreen mode Exit fullscreen mode

Used by platforms like Google, GitHub, and Facebook.
Your app gets an access token after the user grants permission.
Great for third-party integrations and delegated access.

iv.) HMAC (Hash-Based Message Authentication Code)
var key = "secretkey";
var message = "GET:/api/data";
using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key));
var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(message)));

var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-Signature", signature);
var response = await client.GetAsync("https://api.example.com/data");

Enter fullscreen mode Exit fullscreen mode

Uses a shared secret to hash requests, ensuring data integrity. Best for secure system-to-system communication.

What’s your preferred API authentication method?
Share your thoughts below in comments👇

Top comments (0)