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

配置Swagger OpenIdConnect安全方案致加载swagger/undefined报错

问题原因

将Swagger安全定义类型设置为SecuritySchemeType.OpenIdConnect时,Swagger UI 强制要求配置OIDC发现文档地址参数。现有代码缺失该必填配置,前端渲染时无法获取OIDC相关端点路径,拼接请求地址时出现undefined字段,最终导致Swagger页面加载失败。

注释Type = SecuritySchemeType.OpenIdConnect行后,安全方案回退为通用OAuth2类型,不会校验OIDC专属配置项,因此页面可正常加载,但无法启用标准OIDC能力。

修复方案

1. 补全AddSwaggerGen中的OIDC必填配置

在OpenApiSecurityScheme配置块中,新增OpenIdConnectUrl属性,指向Microsoft Identity的OIDC发现文档地址,地址格式为https://login.microsoftonline.com/{你的租户ID}/v2.0/.well-known/openid-configuration。
同时新增全局安全要求过滤器,让所有接口默认应用OIDC认证规则,修正后的配置代码如下:

builder.Services.AddSwaggerGen(options =>
{
    options.AddSecurityDefinition("oidc", new OpenApiSecurityScheme
    {
        Type = SecuritySchemeType.OpenIdConnect,
        // 补全OIDC发现文档地址(必填项,缺失就会触发undefined路径错误)
        OpenIdConnectUrl = new Uri($"https://login.microsoftonline.com/{tenantId}/v2.0/.well-known/openid-configuration"),
        Flows = new OpenApiOAuthFlows
        {
            AuthorizationCode = new OpenApiOAuthFlow
            {
                AuthorizationUrl = new Uri($"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/authorize"),
                TokenUrl = new Uri($"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token"),
                Scopes = new Dictionary<string, string>
                {
                    { "openid", "启用OIDC身份认证" },
                    // 可根据自身API需求追加其他权限范围
                    // { "api://{你的API客户端ID}/user_impersonation", "访问API的用户代理权限" }
                }
            }
        }
    });

    // 新增全局安全要求,让所有接口默认携带认证信息
    options.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "oidc"
                }
            },
            new[] { "openid" }
        }
    });
});

2. 补全Swagger UI的OAuth交互配置

在UseSwaggerUI配置块中,补充授权码流对应的客户端参数,开启PKCE校验(Microsoft Identity v2.0端点强制要求公共客户端使用PKCE),配置示例如下:

app.UseSwaggerUI(options =>
{
    options.OAuthClientId("{你在Microsoft Identity平台注册的Swagger客户端ID}");
    options.OAuthScopes("openid");
    options.OAuthUsePkce(); // 启用PKCE,适配平台安全要求
});

配置注意事项

  • 需提前在Microsoft Identity平台的应用注册中,为Swagger客户端配置正确的重定向URI,格式为{Swagger站点根地址}/oauth2-redirect.html,本地调试时通常为https://localhost:{调试端口}/oauth2-redirect.html
  • 不要混用SecuritySchemeType.OAuth2和SecuritySchemeType.OpenIdConnect的配置逻辑,后者必须显式指定OpenIdConnectUrl,否则必然出现前端路径拼接错误
  • 如果不需要严格遵循OIDC标准,仅需实现Microsoft Identity的OAuth2授权登录,也可将Type改为SecuritySchemeType.OAuth2,此时无需配置OpenIdConnectUrl即可正常使用,但不属于标准OIDC配置方案

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 07:06:11