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

.NET 7 API集成ADFS OpenID Connect引发栈溢出异常求助

问题排查与修复方案

核心问题定位

你的API配置犯了场景匹配错误:AddOpenIdConnect是为交互式Web应用(如MVC)设计的,用于跳转至ADFS完成登录流程,但前后端分离架构下的API是资源服务器,只需要验证前端传来的JWT令牌,应该使用AddJwtBearer而非AddOpenIdConnect。原配置用OpenIdConnect作为Bearer认证方案,会导致中间件处理请求时陷入循环逻辑,最终引发栈溢出。

修复步骤

1. 替换认证方案为JwtBearer

将原认证配置替换为以下代码:

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;

// 服务配置部分
services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    options.Authority = configuration["Authority"]; // 格式:https://adfs.<company>.local/adfs
    options.Audience = configuration["ClientId"]; // 匹配ADFS应用组的服务器应用ID
    options.RequireHttpsMetadata = false; // 生产环境必须设为true
    
    // 处理ADFS自签名证书的验证逻辑
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidIssuer = $"{configuration["Authority"]}/",
        ValidAudience = configuration["ClientId"],
        ValidateIssuerSigningKey = true,
        // 从ADFS元数据获取签名密钥,兼容自签名场景
        IssuerSigningKeyResolver = (token, securityToken, kid, parameters) =>
        {
            var configManager = new ConfigurationManager<OpenIdConnectConfiguration>(
                $"{options.Authority}/.well-known/openid-configuration",
                new OpenIdConnectConfigurationRetriever());
            var config = configManager.GetConfigurationAsync(CancellationToken.None).GetAwaiter().GetResult();
            return config.SigningKeys;
        }
    };
});

2. 调整认证中间件应用范围

在Program.cs中正确挂载认证/授权中间件,同时确保匿名路由标记[AllowAnonymous]:

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

// 示例:匿名健康检查路由
app.MapGet("/api/health", () => Results.Ok("Healthy"))
   .AllowAnonymous();

// 示例:需要认证的受保护路由
app.MapGet("/api/protected", () => Results.Ok("Protected content"))
   .RequireAuthorization();

3. 验证前端JWT的正确性

确认NextAuth获取的JWT满足以下要求:

  • aud声明必须严格匹配API的ClientId
  • iss声明必须为ADFS的Authority地址(如https://adfs.<company>.local/adfs/)
  • 令牌签名由ADFS的签名证书生成,API可通过元数据端点获取该证书

额外注意事项

  • 生产环境必须启用RequireHttpsMetadata = true,并将ADFS的自签名证书导入API服务器的受信任根证书存储,禁止使用开发环境的证书验证绕过逻辑。
  • 若仍有异常,可在appsettings.json中开启详细认证日志排查:
{
  "Logging": {
    "LogLevel": {
      "Microsoft.AspNetCore.Authentication": "Debug"
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 13:47:31