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

Swashbuckle 6.3.0如何仅在指定Swagger文档显示Authorize按钮

解决方法

Swashbuckle 6.x 版本中,Swagger UI顶部的Authorize按钮渲染逻辑为:读取当前加载文档根节点的Components.SecuritySchemes集合,集合非空时显示按钮,为空时自动隐藏。通过自定义文档过滤器按文档名单独注入安全定义即可实现需求,无需注入自定义前端脚本。

步骤1:移除全局安全定义注册

删除AddSwaggerGen配置块中原先全局调用的options.AddSecurityDefinition("Bearer", ...)代码,该方法会将安全定义注入所有生成的Swagger文档,无法单独隔离。

步骤2:自定义文档过滤器按需注入安全定义

新建实现IDocumentFilter接口的过滤器类,仅在集成接口文档生成时注入Bearer认证的安全定义:

public class BearerSecurityDocumentFilter : IDocumentFilter
{
    public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
    {
        // 非集成接口文档直接返回,不注入安全定义
        if (context.DocumentName != SwaggerConfiguration.IntegrationApiVersion)
        {
            return;
        }

        // 仅给集成接口文档添加Bearer认证安全定义
        swaggerDoc.Components.SecuritySchemes.Add("Bearer", new OpenApiSecurityScheme
        {
            Description = "Bearer Token: e.g. \"Bearer <your token here>\"",
            Name = "Authorization",
            In = ParameterLocation.Header,
            Type = SecuritySchemeType.ApiKey,
            Scheme = "Bearer",
            Reference = new OpenApiReference
            {
                Id = "Bearer",
                Type = ReferenceType.SecurityScheme
            }
        });
    }
}

步骤3:注册过滤器到Swagger配置

在AddSwaggerGen配置块中注册上述文档过滤器,原有TestOperationFilter保留无需修改,调整后的配置如下:

services.AddSwaggerGen(
    options =>
    {
        options.SwaggerDoc(
            IntegrationApiVersion, 
            new OpenApiInfo { Title = IntegrationApiName, Version = IntegrationApiVersion });
        options.SwaggerDoc(
            ApplicationApiVersion, 
            new OpenApiInfo { Title = ApplicationApiName, Version = ApplicationApiVersion });

        // 注册自定义文档过滤器替换原全局AddSecurityDefinition逻辑
        options.DocumentFilter<BearerSecurityDocumentFilter>();

        options.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
        options.EnableAnnotations();
        options.SchemaFilter<SmartEnumSchemaFilter>();

        options.SupportNonNullableReferenceTypes();
        options.UseAllOfToExtendReferenceSchemas();
        options.IncludeXmlComments(
            Path.Combine(AppContext.BaseDirectory, $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"),
            includeControllerXmlComments: true);

        // 原有操作过滤器保留,用于给需要认证的接口显示锁标识
        options.OperationFilter<TestOperationFilter>();
    })
.AddFluentValidationRulesToSwagger();

最终效果

  • 集成接口文档页:顶部正常显示Authorize按钮,接口旁锁标识正常展示,JWT认证逻辑完全不受影响
  • 应用接口文档页:顶部Authorize按钮自动隐藏,无任何认证相关入口

该方案基于Swashbuckle内置扩展点实现,兼容6.x全版本,无需修改Swagger UI静态资源,不会随版本升级失效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 03:45:36