如何隐藏Swagger UI中的安全端点但保留在swagger.json中
如何在Swagger UI隐藏安全端点但保留在swagger.json中
Spring Boot 场景(Springdoc / Springfox)
方法1:Springdoc 自定义UI过滤器
实现SwaggerUiCustomizer接口,指定要隐藏的路径规则,Swagger UI会屏蔽这些路径,但swagger.json不受影响:
@Component public class HideSecureEndpointsCustomizer implements SwaggerUiCustomizer { @Override public void customize(SwaggerUiConfigParameters params) { // 填入需要隐藏的端点路径,支持通配符 params.setHiddenPaths(List.of("/admin/**", "/internal/api/**")); } }
方法2:Springfox 注解标记拦截
先定义自定义注解标记需要隐藏的接口,再通过插件拦截UI展示逻辑:
// 自定义注解 @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface HideInSwaggerUi {} // 实现插件 @Component public class HideEndpointPlugin implements OperationBuilderPlugin { @Override public void apply(OperationContext context) { if (context.findAnnotation(HideInSwaggerUi.class).isPresent()) { context.operationBuilder().hidden(true); } } @Override public boolean supports(DocumentationType delimiter) { return delimiter == DocumentationType.SWAGGER_2; } }
给需要隐藏的控制器或方法加上@HideInSwaggerUi即可,该设置仅影响Swagger UI展示,不会删除swagger.json中的定义。
ASP.NET Core 场景
通过自定义特性+操作过滤器实现:
// 自定义标记特性 [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)] public class HideInSwaggerUiAttribute : Attribute {} // 实现操作过滤器 public class HideInSwaggerUiFilter : IOperationFilter { public void Apply(OpenApiOperation operation, OperationFilterContext context) { var hasHideAttr = context.MethodInfo.GetCustomAttribute<HideInSwaggerUiAttribute>() != null || context.MethodInfo.DeclaringType.GetCustomAttribute<HideInSwaggerUiAttribute>() != null; if (hasHideAttr) { // 添加Swagger UI识别的隐藏扩展属性 operation.Extensions.Add("x-hidden", new OpenApiBoolean(true)); } } }
在配置Swagger时注册过滤器:
builder.Services.AddSwaggerGen(c => { c.OperationFilter<HideInSwaggerUiFilter>(); });
通用OpenAPI规范方案
直接给需要隐藏的操作添加OpenAPI扩展属性x-hidden: true,Swagger UI会自动识别并隐藏该端点,但swagger.json会完整保留定义。例如在OpenAPI YAML中手动配置:
paths: /secure/confidential: post: x-hidden: true summary: 敏感操作接口 responses: '200': description: 操作成功
内容的提问来源于stack exchange,提问作者Pradeep Yadav
相关产品推荐
相关产品推荐

