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

huangapple go评论76阅读模式
英文:

SpringBoot-OpenAPI: How to add default header to all requests

问题

以下是翻译好的内容:

现在,我想要在所有请求中添加一个额外的头部MyCustomHeader: MyValue,该如何实现?

英文:

I have created an OpenAPI spec as below.

    @Bean
    public OpenAPI customOpenAPI() {
        final String securitySchemeName = "Authorization";
        final String apiTitle = "My Service";
        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));
    }

Now, I want OpenAPI UI to add one extra header MyCustomHeader:MyValue to all the requests. How can I achieve this?

答案1

得分: 1

你可以按照以下方式定义OpenApiCustomiser bean:

@Bean
public OpenApiCustomiser openApiCustomizer() {
  return openApi -> openApi.getPaths().values().stream()
      .flatMap(pathItem -> pathItem.readOperations().stream())
      .forEach(
          operation -> operation.addParametersItem(
              new HeaderParameter()
                  .schema(new StringSchema()._default("MyValue"))
                  .name("MyCustomHeader")));
}

这个bean将MyCustomHeader头部添加到所有以MyValue为默认值的端点上。

英文:

You can define OpenApiCustomiser bean as follows:

@Bean
public OpenApiCustomiser openApiCustomizer() {
  return openApi ->
      openApi.getPaths().values().stream()
          .flatMap(pathItem -> pathItem.readOperations().stream())
          .forEach(
              operation ->
                  operation.addParametersItem(
                      new HeaderParameter()
                          .schema(new StringSchema()._default("MyValue"))
                          .name("MyCustomHeader")));
}

The bean adds the MyCustomHeader header to all endpoints with MyValue
as default value.

huangapple
  • 本文由 发表于 2023年2月13日 23:44:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75438134.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定