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

ASP.NET Core Web API:如何用Basic Auth凭证授权Get请求?

在ASP.NET Core 6 Web API中实现Basic Auth验证

按照你的需求,我们可以通过自定义授权策略实现基于appsettings配置的Basic Auth验证,具体步骤如下:

1. 创建配置绑定类

先创建类来绑定appsettings.json中的BasicCredentials配置:

public class BasicCredentials
{
    public string Username { get; set; }
    public string Password { get; set; }
}

2. 注册配置到依赖注入容器

在Program.cs中添加配置绑定逻辑:

// 绑定BasicCredentials节点的配置
builder.Services.Configure<BasicCredentials>(builder.Configuration.GetSection("BasicCredentials"));

3. 实现Basic Auth授权验证逻辑

创建自定义授权要求和处理器,用于校验请求头中的凭证:

自定义授权要求

public class BasicAuthRequirement : IAuthorizationRequirement { }

授权处理器

public class BasicAuthHandler : AuthorizationHandler<BasicAuthRequirement>
{
    private readonly IOptions<BasicCredentials> _configCredentials;

    public BasicAuthHandler(IOptions<BasicCredentials> configCredentials)
    {
        _configCredentials = configCredentials;
    }

    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, BasicAuthRequirement requirement)
    {
        if (context.Resource is not HttpContext httpContext)
        {
            return Task.CompletedTask;
        }

        var authHeader = httpContext.Request.Headers.Authorization.FirstOrDefault();
        // 检查授权头格式是否合法
        if (string.IsNullOrEmpty(authHeader) || !authHeader.StartsWith("Basic "))
        {
            httpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
            httpContext.Response.Headers.WWWAuthenticate = "Basic";
            return Task.CompletedTask;
        }

        // 解码Base64格式的凭证内容
        var encodedContent = authHeader.Substring("Basic ".Length).Trim();
        var decodedBytes = Convert.FromBase64String(encodedContent);
        var credentialParts = Encoding.UTF8.GetString(decodedBytes).Split(':', 2);

        if (credentialParts.Length != 2)
        {
            httpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
            httpContext.Response.Headers.WWWAuthenticate = "Basic";
            return Task.CompletedTask;
        }

        // 校验凭证是否匹配配置值
        var (requestUsername, requestPassword) = (credentialParts[0], credentialParts[1]);
        if (requestUsername == _configCredentials.Value.Username && requestPassword == _configCredentials.Value.Password)
        {
            context.Succeed(requirement);
        }
        else
        {
            httpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
            httpContext.Response.Headers.WWWAuthenticate = "Basic";
        }

        return Task.CompletedTask;
    }
}

4. 注册授权服务

在Program.cs中添加授权策略和处理器注册:

// 添加自定义授权策略
builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("BasicAuth", policy =>
        policy.Requirements.Add(new BasicAuthRequirement()));
});

// 注册授权处理器
builder.Services.AddScoped<IAuthorizationHandler, BasicAuthHandler>();

5. 为接口添加授权验证

在需要验证的Get/Post/Put接口上添加[Authorize(Policy = "BasicAuth")]特性,以你的GetEmployees接口为例:

[HttpGet]
[Authorize(Policy = "BasicAuth")]
public IEnumerable<Employee> GetEmployees()
{
    List<Employee> employeelist = new List<Employee>();
    // 使用局部变量+using块自动释放资源,避免全局变量导致的连接泄漏
    using (var con = new SqlConnection(connection))
    {
        con.Open();
        using (var command = new SqlCommand("sp_employees", con))
        {
            command.CommandType = CommandType.StoredProcedure;
            using (var dataReader = command.ExecuteReader())
            {
                while (dataReader.Read())
                {
                    Employee employee = new Employee();
                    employee.EmployeeId = Convert.ToInt32(dataReader["EmployeeId"]);
                    employee.Firstname = dataReader["Firstname"].ToString();
                    employee.Lastname = dataReader["Lastname"].ToString();
                    employee.Email = dataReader["Email"].ToString();
                    employee.EmploymentDate = Convert.ToDateTime(dataReader["EmploymentDate"]);

                    employeelist.Add(employee);
                }
            }
        }
        // using块会自动关闭连接,无需手动调用con.Close()
    }
    return employeelist;
}

6. 客户端请求示例

客户端需要将Akwetey:#12345677**87编码为Base64字符串,然后添加到请求头:

curl --location 'https://your-api-domain/employees' \
--header 'Authorization: Basic QWt3ZXRleTojMTIzNDU2NzcqKjg3'

注:上述Base64字符串是Akwetey:#12345677**87的编码结果,可自行验证生成


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 01:15:43