前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >dotnet 使用 HttpClient 时如何使用 Basic 认证?

dotnet 使用 HttpClient 时如何使用 Basic 认证?

原创
作者头像
Power
发布2025-04-02 00:13:59
发布2025-04-02 00:13:59
14200
代码可运行
举报
运行总次数:0
代码可运行

Basic Access Authentication 是一种简单的 HTTP 认证机制,用于通过用户名和密码保护 Web 资源的访问。它的工作原理如下:

  1. 客户端请求访问受保护的资源:当客户端(如浏览器)尝试访问受保护的资源时,服务器返回一个 HTTP 401 未授权状态码,并在响应头中包含一个 WWW-Authenticate 头,指示需要基本认证。
  2. 客户端发送凭据:客户端再次发送请求,这次在请求头中包含一个 Authorization 头。这个头的值是字符串 Basic后面跟着 base64 编码的“用户名:密码”组合。
  3. 服务器验证凭据:服务器解码 base64 编码的凭据,提取用户名和密码,并验证这些凭据是否正确。如果正确,则允许访问资源,否则返回 HTTP 401 状态码。

如果要在 HttpClient 中使用基本身份验证,只需创建一个 HttpRequestMessage 并添加以下请求头:

代码语言:javascript
代码运行次数:0
运行
复制
var request = new HttpRequestMessage(HttpMethod.Post, getPath)
{
    Content = new FormUrlEncodedContent(values)
};
request.Headers.Authorization = new BasicAuthenticationHeaderValue("username", "password");
// other settings

BasicAuthenticationHeaderValue 来自 IdentityModel 包。如果你不想引用这个重重的家伙,可以直接使用以下代码:

代码语言:javascript
代码运行次数:0
运行
复制
/// <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 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档