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

SpringBoot-OpenAPI:如何为所有请求添加默认请求头

实现OpenAPI UI自动添加全局请求头的两种方案

方案一:通过OpenAPI全局参数配置(文档可见)

这种方式会在API文档中显示该请求头,同时UI会自动填充默认值,发送请求时自动携带。

修改你现有的customOpenAPI() Bean,添加全局请求参数配置:

@Bean
public OpenAPI customOpenAPI() {
    final String securitySchemeName = "Authorization";
    final String apiTitle = "My Service";
    
    // 定义自定义请求头参数
    Parameter customHeader = new Parameter()
            .name("MyCustomHeader")
            .in("header")
            .required(false) // 根据业务需求设置是否必填
            .schema(new StringSchema().defaultValue("MyValue"))
            .description("自定义全局请求头");

    return new OpenAPI()
            .addSecurityItem(new SecurityRequirement().addList(securitySchemeName))
            .components(
                    new Components()
                            .addSecuritySchemes(securitySchemeName,
                                    new SecurityScheme()
                                            .name(securitySchemeName)
                                            .type(SecurityScheme.Type.APIKEY)
                                            .in(SecurityScheme.In.HEADER)))
            .info(new Info().title(apiTitle))
            .addGlobalParameter(customHeader); // 添加全局参数
}

配置完成后,OpenAPI UI的所有请求都会自动带上MyCustomHeader:MyValue,同时这个参数会出现在每个接口的请求头列表中,用户也可以在UI中修改该值。

方案二:通过Swagger UI拦截器配置(文档不可见)

如果不想在API文档中暴露这个请求头,仅需要UI自动携带固定值,可以通过配置SwaggerUiConfigProperties添加请求拦截器:

@Configuration
public class SwaggerUiConfig {

    @Bean
    public SwaggerUiConfigProperties swaggerUiConfigProperties() {
        SwaggerUiConfigProperties properties = new SwaggerUiConfigProperties();
        
        // 添加请求拦截器,自动注入自定义请求头
        String requestInterceptor = "() => { return { requestInterceptor: (req) => { req.headers['MyCustomHeader'] = 'MyValue'; return req; } } }";
        properties.setRequestInterceptor(requestInterceptor);
        
        return properties;
    }
}

这种方式下,API文档中不会显示该请求头,但每次通过UI发送请求时,都会自动添加MyCustomHeader:MyValue,且用户无法在UI界面修改该值。

注意事项

  • 方案一支持用户在UI中修改请求头值,方案二则强制使用固定值,可根据业务场景选择。
  • 确保项目依赖了兼容版本的SpringDoc相关包(例如springdoc-openapi-starter-webmvc-ui)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 15:15:16