Basic Access Authentication 是一种简单的 HTTP 认证机制,用于通过用户名和密码保护 Web 资源的访问。它的工作原理如下:
WWW-Authenticate
头,指示需要基本认证。Authorization
头。这个头的值是字符串 Basic
后面跟着 base64 编码的“用户名:密码”组合。如果要在 HttpClient 中使用基本身份验证,只需创建一个 HttpRequestMessage 并添加以下请求头:
var request = new HttpRequestMessage(HttpMethod.Post, getPath)
{
Content = new FormUrlEncodedContent(values)
};
request.Headers.Authorization = new BasicAuthenticationHeaderValue("username", "password");
// other settings
BasicAuthenticationHeaderValue 来自 IdentityModel 包。如果你不想引用这个重重的家伙,可以直接使用以下代码:
/// <summary>
/// HTTP Basic Authentication authorization header
/// </summary>
/// <seealso cref="System.Net.Http.Headers.AuthenticationHeaderValue" />
public class BasicAuthenticationHeaderValue : AuthenticationHeaderValue
{
/// <summary>
/// Initializes a new instance of the <see cref="BasicAuthenticationHeaderValue"/> class.
/// </summary>
/// <param name="userName">Name of the user.</param>
/// <param name="password">The password.</param>
public BasicAuthenticationHeaderValue(string userName, string password)
: base("Basic", EncodeCredential(userName, password))
{ }
/// <summary>
/// Encodes the credential.
/// </summary>
/// <param name="userName">Name of the user.</param>
/// <param name="password">The password.</param>
/// <returns></returns>
/// <exception cref="ArgumentNullException">userName</exception>
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));
}
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。