You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C# ASP.NET Web API中传递客户端认证凭证至NetworkCredential方法

问题:ASP.NET Web API动态传递请求头Basic认证信息到NetworkCredential方法

我已搭建一个ASP.NET Web API,希望动态验证请求头中提供的Basic认证信息(用户名和Web访问密钥),并将其传入已配置的NetworkCredential方法进行验证。

现有代码

模型类

public class Customer
{
    public string No_;
    public string Name;
    public string AccountingLocation;
}

控制器方法

public IHttpActionResult Get(string id)
{
    try
    {
            ws.ValidationRegWebService();
            Validation.Customer customerVal = new Validation.Customer();
            customerVal = ws.validationReg_ws.Read(id);
            [...]
     }
     [...]
 }

NetworkCredential方法

public NetworkCredential Credential() 
{
   NetworkCredential cred = new NetworkCredential
   {
         UserName = globals.UserName,
         Password = globals.Password
    };
    return cred;
}

(附Postman认证设置截图)

请问如何将客户端的认证信息传递到该NetworkCredential方法中?


解决方案

1. 从请求头解析Basic认证信息

Basic认证的请求头格式为 Authorization: Basic <base64编码的用户名:密码>,需要先提取并解码:

private (string Username, string Password) GetBasicAuthCredentials()
{
    var authHeader = Request.Headers.Authorization;
    if (authHeader == null || !authHeader.Scheme.Equals("Basic", StringComparison.OrdinalIgnoreCase))
    {
        throw new UnauthorizedAccessException("未提供有效的Basic认证信息");
    }

    // 解码Base64字符串
    var encodedCredentials = authHeader.Parameter;
    var decodedBytes = Convert.FromBase64String(encodedCredentials);
    var credentials = Encoding.UTF8.GetString(decodedBytes).Split(':');
    
    if (credentials.Length != 2)
    {
        throw new UnauthorizedAccessException("Basic认证格式错误");
    }

    return (credentials[0], credentials[1]);
}

2. 修改NetworkCredential方法,支持动态传入参数

将原方法改为接受用户名和密码作为参数,替代硬编码的全局变量值:

public NetworkCredential Credential(string userName, string password) 
{
    return new NetworkCredential
    {
        UserName = userName,
        Password = password
    };
}

3. 在控制器中集成认证逻辑

在Get方法开头先获取并验证认证信息,再将其传入Credential方法,绑定到Web服务客户端:

public IHttpActionResult Get(string id)
{
    try
    {
        // 获取并验证请求头中的Basic认证信息
        var (username, password) = GetBasicAuthCredentials();
        
        // 生成动态的NetworkCredential
        var cred = Credential(username, password);
        
        // 将凭证绑定到Web服务代理实例
        ws.Credentials = cred;
        
        ws.ValidationRegWebService();
        Validation.Customer customerVal = ws.validationReg_ws.Read(id);
        // ...后续业务逻辑
    }
    catch (UnauthorizedAccessException ex)
    {
        return Unauthorized(); // 返回401未授权状态码
    }
    catch (Exception ex)
    {
        // 处理其他异常
        return InternalServerError(ex);
    }
}

补充说明

  • 如果需要全局验证所有接口的Basic认证,可以使用ActionFilterAttribute或AuthenticationFilterAttribute,避免在每个控制器方法中重复编写认证逻辑。
  • 生产环境中必须配合HTTPS使用Basic认证,防止凭证被明文窃取。

内容的提问来源于stack exchange,提问作者hopeforall

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 18:43:33