我想使用授权策略将 API 密钥身份验证添加到我的 API,但收到错误
No authenticationScheme was specified, and there was no DefaultChallengeScheme found. The default schemes can be set using either AddAuthentication(string defaultScheme) or AddAuthentication(Action<AuthenticationOptions> configureOptions).
有办法做到这一点吗?
我不需要任何 cookie/JWT 身份验证,API 密钥将作为标头发送。
这是我的配置:
public class ApiKeyRequirement : IAuthorizationRequirement
{
public ApiKeyRequirement()
{
}
}
public class ApiKeyHandler(IHttpContextAccessor httpContextAccessor, IConfiguration configuration) : AuthorizationHandler<ApiKeyRequirement>
{
private readonly string apiKey = configuration["Credentials:ApiKey"] ?? throw new Exception("No API key was found");
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, ApiKeyRequirement requirement)
{
string? receivedApiKey = httpContextAccessor.HttpContext!.Request.Headers["x-api-key"];
if (receivedApiKey != apiKey)
{
return Task.CompletedTask;
}
context.Succeed(requirement);
return Task.CompletedTask;
}
}
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("ApiKey", policy =>
{
policy.Requirements.Add(new ApiKeyRequirement());
});
});
//...
app.UseAuthorization();
但我收到错误
No authenticationScheme was specified, and there was no DefaultChallengeScheme found. The default schemes can be set using either AddAuthentication(string defaultScheme) or AddAuthentication(Action<AuthenticationOptions> configureOptions).
您不需要任何 cookie/JWT 身份验证,只需将 API 密钥作为标头发送。如果您通过测试代码发送正确的 api 密钥,那么您所做的实际上可以正常工作。为什么您收到错误可能是由于您发送了错误的 api key 或您没有在标头中发送 api key。
您需要在 ApiKeyHandler 中设置断点来检查 api 密钥是否正确: