在 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。
529

被折叠的 条评论
为什么被折叠?



