ASP .NET Core 中的 Api Key 身份验证之二【AuthenticationHandler】

在 ASP.NET Core 中实现 API Key 身份验证可以通过自定义中间件或 AuthenticationHandler 来完成。下面是实现 API Key 身份验证的详细步骤和代码示例:

1. 创建 API Key 认证方案

AuthenticationHandler 中定义自定义身份验证逻辑。

1.1 创建 ApiKeyAuthenticationHandler

在项目中创建 Authentication 文件夹,并新建类 ApiKeyAuthenticationHandler

using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Security.Claims;
using System.Text.Encodings.Web;
using System.Threading.Tasks;

public class ApiKeyAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
    private const string ApiKeyHeaderName = "X-API-KEY";
    private readonly string _apiKey;

    public ApiKeyAuthenticationHandler(
        IOptionsMonitor<AuthenticationSchemeOptions> options,
        ILoggerFactory logger,
        UrlEncoder encoder,
        ISystemClock clock,
        IConfiguration configuration)
        : base(options, logger, encoder, clock)
    {
        _apiKey = configuration["ApiKey"]; // 从配置中读取 API Key
    }

    protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        if (!Request.Headers.TryGetValue(ApiKeyHeaderName, out var apiKeyHeaderValues))
        {
            return AuthenticateResult.Fail("API Key header not found.");
        }

        var apiKey = apiKeyHeaderValues.FirstOrDefault();
        if (apiKey == null || apiKey != _apiKey)
        {
            return AuthenticateResult.Fail("Invalid API Key.");
        }

        var claims = new[] { new Claim(ClaimTypes.Name, "API User") };
        var identity = new ClaimsIdentity(claims, Scheme.Name);
        var principal = new ClaimsPrincipal(identity);
        var ticket = new AuthenticationTicket(principal, Scheme.Name);

        return AuthenticateResult.Success(ticket);
    }
}

2. 配置身份验证服务

Program.cs 文件中注册身份验证服务。

var builder = WebApplication.CreateBuilder(args);

// 添加身份验证
builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = "ApiKey";
    options.DefaultChallengeScheme = "ApiKey";
}).AddScheme<AuthenticationSchemeOptions, ApiKeyAuthenticationHandler>("ApiKey", null);

builder.Services.AddControllers();

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();

3. 配置 API Key

appsettings.json 文件中添加 API Key:

{
  "ApiKey": "MySecretApiKey123"
}

4. 创建测试 Controller

创建 TestController 进行身份验证测试。

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class TestController : ControllerBase
{
    [HttpGet]
    [Authorize]
    public IActionResult Get()
    {
        return Ok("API Key is valid");
    }
}

5. 发送请求测试

请求示例(Postman 或 cURL)

请求地址:

GET http://localhost:5000/api/test

请求头:

X-API-KEY: MySecretApiKey123

响应:

"API Key is valid"

如果 API Key 不正确或缺失,将返回 401 Unauthorized

6. 安全性增强

  • 使用加密方式存储 API Key。
  • 支持多密钥或动态密钥验证。
  • 设置 API Key 的过期时间。
  • 限制特定 API 接口使用 API Key。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值