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

ASP.NET Core 8中AddScheme未配置选项的问题排查

ASP.NET Core 8 自定义ApiKey身份验证配置未执行问题

我在ASP.NET Core 8中搭建自定义ApiKey身份验证方案,已创建ApiKeyAuthenticationOptions和ApiKeyAuthenticationHandler,但启动时发现AddScheme中的选项配置代码始终未执行——设置的断点从未触发,且当ApiKey为空时,空合并运算符右侧的异常也未抛出。

相关代码:

Program.cs 中的身份验证配置:

builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = ApiKeyAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = ApiKeyAuthenticationDefaults.AuthenticationScheme;
})
    .AddScheme<ApiKeyAuthenticationOptions, ApiKeyAuthenticationHandler>(ApiKeyAuthenticationDefaults.AuthenticationScheme, options =>
    {
        options.ApiKey = configuration["ApiKey"] ?? throw new Exception("No API key was configured");
    });

ApiKeyAuthenticationHandler 实现:

namespace API.Authentication.ApiKeyAuthenticaiton
{
    public class ApiKeyAuthenticationHandler : AuthenticationHandler<ApiKeyAuthenticationOptions>
    {
        public ApiKeyAuthenticationHandler(IOptionsMonitor<ApiKeyAuthenticationOptions> options,
            ILoggerFactory logger,
            UrlEncoder encoder) : base(options, logger, encoder)
        {
            ApiKeyAuthenticationOptions opts = options.CurrentValue;

            if (opts.ApiKey == null) throw new ArgumentNullException(nameof(opts.ApiKey));
        }

        protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
        {
            // Validate API key
            
            if (!Request.Headers.TryGetValue("x-api-key", out var key)) return AuthenticateResult.Fail("Missing API key");
            if (key != Options.ApiKey) return AuthenticateResult.Fail("Invalid API key");

            return AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(), Scheme.Name));
        }
    }
}

ApiKeyAuthenticationOptions 定义:

public class ApiKeyAuthenticationOptions : AuthenticationSchemeOptions
{
    public string ApiKey { get; set; } = null!;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 10:05:16