Basic Access Authentication 是一种简单的 HTTP 认证机制,用于通过用户名和密码保护 Web 资源的访问。它的工作原理如下:
- 客户端请求访问受保护的资源:当客户端(如浏览器)尝试访问受保护的资源时,服务器返回一个 HTTP 401 未授权状态码,并在响应头中包含一个
WWW-Authenticate头,指示需要基本认证。 - 客户端发送凭据:客户端再次发送请求,这次在请求头中包含一个
Authorization头。这个头的值是字符串Basic后面跟着 base64 编码的“用户名:密码”组合。 - 服务器验证凭据:服务器解码 base64 编码的凭据,提取用户名和密码,并验证这些凭据是否正确。如果正确,则允许访问资源,否则返回 HTTP 401 状态码。
如果要在 HttpClient 中使用基本身份验证,只需创建一个 HttpRequestMessage 并添加以下请求头:
var request = new HttpRequestMessage(HttpMethod.Post, getPath)
{
Content = new FormUrlEncodedContent(values)
};
request.Headers.Authorization = new BasicAuthenticationHeaderValue("username", "password");
// other settings
BasicAuthenticationHeaderValue 来自 IdentityModel 包。如果你不想引用这个重重的家伙,可以直接使用以下代码:
////// HTTP Basic Authentication authorization header /// /// public class BasicAuthenticationHeaderValue : AuthenticationHeaderValue { ////// Initializes a new instance of the class. /// /// Name of the user. /// The password. public BasicAuthenticationHeaderValue(string userName, string password) : base("Basic", EncodeCredential(userName, password)) { } ////// Encodes the credential. /// /// Name of the user. /// The password. /// /// userName public static string EncodeCredential(string userName, string password) { if (string.IsNullOrWhiteSpace(userName)) throw new ArgumentNullException(nameof(userName)); if (password == null) password = ""; Encoding encoding = Encoding.UTF8; string credential = String.Format("{0}:{1}", userName, password); return Convert.ToBase64String(encoding.GetBytes(credential)); } }










