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

.NET Core 3.1中Swagger Swashbuckle Bearer授权无法携带问题排查

问题分析与解决

你的问题出在SecurityDefinition和SecurityRequirement的配置不匹配,导致Swagger无法正确将获取到的token填充到Authorization头中,从而出现Bearer undefined的情况。

具体错误点

  1. 你定义的Bearer SecurityScheme类型是OAuth2(用于Password流获取token),但在SecurityRequirement中却重新创建了一个Http类型的Scheme,两者没有正确关联。
  2. SecurityRequirement中重复定义了Scheme的属性,这些属性应该直接引用已定义的SecurityScheme,而非重新声明。

修正后的配置代码

services.AddSwaggerGen(c => {
    c.SwaggerDoc("v1", new OpenApiInfo() { Title = "MyApi", Version = "v1" });
    // Set the comments path for the Swagger JSON and UI.
    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
    c.IncludeXmlComments(xmlPath);
    
    // 定义OAuth2 Password流的SecurityScheme
    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme {
        Type = SecuritySchemeType.OAuth2,
        Flows = new OpenApiOAuthFlows() {
            Password = new OpenApiOAuthFlow() {
                TokenUrl = new Uri("/api/Account/Login", UriKind.Relative),
                Scopes = new Dictionary<string, string>() // 如果API有Scope需求,可在此添加
                {
                    // {"read_access", "Read access to API"},
                    // {"write_access", "Write access to API"}
                }
            }
        },
        Description = "输入用户名和密码获取Bearer Token"
    });
    
    // 引用已定义的SecurityScheme,确保关联正确
    c.AddSecurityRequirement(new OpenApiSecurityRequirement {
        {
            new OpenApiSecurityScheme {
                Reference = new OpenApiReference {
                    Type = ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }
            },
            new List<string>() // 若有Scope需求,填写对应列表,否则空列表即可
        }
    });
});

额外配置注意事项

除了上述修正,你还需要在Configure方法中确保Swagger UI启用OAuth支持,添加以下配置:

app.UseSwaggerUI(c => {
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyApi v1");
    // 启用OAuth登录支持
    c.OAuthClientId("swagger-ui-client"); // 后端无特殊要求时可随意填写
    c.OAuthAppName("MyApi Swagger UI");
    c.OAuthUseBasicAuthenticationWithAccessCodeGrant(); // 后端需要客户端认证时保留,否则可移除
});

问题根源解释

当你在SecurityRequirement中重新创建Http类型的Scheme时,Swagger会将其视为独立的Bearer认证方案,和你定义的OAuth2 Password流没有关联。因此即使通过OAuth登录获取到了token,Swagger也不知道要将这个token填充到该Http Scheme对应的请求头中,最终导致Bearer undefined的错误。

修正后,SecurityRequirement直接引用了OAuth2类型的Bearer Scheme,Swagger就能正确将获取到的token以Bearer {token}的格式添加到Authorization头中了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 10:47:49