理解 C# 中的 API 身份验证:精通

发布: (2026年1月8日 GMT+8 16:47)
3 min read
原文: Dev.to

Source: Dev.to

基本身份验证(用户名 & 密码)

基本身份验证会将用户名和密码以 Base64 编码后发送。实现简单,但只能在 HTTPS 上使用,通常适用于内部或测试 API。

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 身份验证(JWT)

Bearer Token(例如 JWT)是无状态且可扩展的,非常适合现代 REST API。

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 提供商(Google、GitHub、Facebook 等)会颁发访问令牌,这些令牌以 Bearer Token 形式发送。此方式在第三方集成中被广泛使用。

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 签名身份验证

HMAC 签名使用共享密钥对请求数据进行哈希,确保请求的真实性和完整性。该方法非常适合安全的系统间通信。

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");

安全注意事项

  • 始终使用 HTTPS 传输凭证或令牌。
  • 切勿以明文形式存储密码;生产环境下更倾向使用基于令牌的方案。
  • 定期轮换密钥和令牌,以降低泄露风险。
  • 在使用 HMAC 时在服务器端验证签名,确保请求完整性。
Back to Blog

相关文章

阅读更多 »

在 C# 中将 RTF 转换为 PDF

概述 RTF(Rich Text Format)是一种跨平台的格式,广泛用于文档编辑和数据交换。相比之下,PDF 则是文档分发的理想选择……