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

ASP.NET Core 8 Minimal API:Swagger集成JWT授权无效问题

ASP.NET Core 8 Minimal API + NSwag v14.0.7 JWT授权问题修复

问题根源

核心问题有三点:

  1. 未在Swagger文档中添加安全要求(Security Requirement),导致Swagger不会将令牌自动附加到API请求头中
  2. 现有安全方案配置不符合JWT标准(使用ApiKey类型而非HttpBearer),可能引发令牌格式识别异常
  3. 可能遗漏了ASP.NET Core本身的认证/授权中间件配置

分步修复

1. 配置ASP.NET Core认证授权基础服务

这是Swagger授权生效的前提,必须先完成:

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;

// 添加JWT认证服务
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            // 替换为你的实际配置项
            ValidIssuer = builder.Configuration["Jwt:Issuer"],
            ValidAudience = builder.Configuration["Jwt:Audience"],
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
        };
    });

// 添加授权服务
builder.Services.AddAuthorization();

然后在中间件管道中启用认证和授权(需放在UseRouting之后、UseEndpoints之前):

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

2. 修正NSwag Swagger文档配置

NSwag v14没有直接的AddSecurityRequirement扩展方法,需在PostProcess回调中手动给生成的OpenApi文档添加安全要求,同时修正安全方案类型:

builder.Services.AddSwaggerDocument(options => {
    options.PostProcess = document => {
        document.Info = new OpenApiInfo
        {
            Version = "v8",
            Title = "API",
            Description = "doc info",
            Contact = new OpenApiContact
            {
                Name = "Dúvidas e suporte",
                Email = "tech@email.com"
            }
        };
        // 添加安全要求,引用之前定义的"bearer"安全方案ID
        document.SecurityRequirements.Add(new OpenApiSecurityRequirement
        {
            {
                new OpenApiSecuritySchemeReference { Id = "bearer" },
                new List<string>()
            }
        });
    };
    // 修正安全方案:使用HttpBearer类型,符合JWT标准
    options.AddSecurity("bearer", new OpenApiSecurityScheme()
    {
        Name = "Authorization",
        In = OpenApiSecurityApiKeyLocation.Header,
        Type = OpenApiSecuritySchemeType.Http, // 替换为Http类型
        Scheme = "bearer",
        BearerFormat = "JWT", // 明确标注令牌格式为JWT
        Description = "请输入格式为 `Bearer {你的JWT令牌}` 的授权信息"
    });
});

3. 给API端点启用授权

在Minimal API中,给受保护的端点添加.RequireAuthorization():

app.MapGet("/api/protected", () => Results.Ok("这是受保护的内容"))
   .RequireAuthorization();

验证效果

  1. 启动项目,打开Swagger页面
  2. 点击授权按钮,输入Bearer 你的JWT令牌(注意Bearer与令牌之间有空格)
  3. 调用受保护端点,此时请求头会自动带上Authorization: Bearer xxx,应能正常返回数据而非401

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 07:35:57