openapi 3.0 中所有 API 的强制性 header

Mandatory header for all API in openapi 3.0

我正在使用带有 Spring-boot 5 的 OpenAPI 3.0,因此没有配置 YAML。我有一个包含客户端标识 ID 的 header(这不是身份验证 header)。我想让它成为强制性的 header 参数。在打开API 配置

下方添加
@Configuration
public class OpenAPIConfiguration {
    @Bean
    public OpenAPI customOpenAPI() {

        return new OpenAPI()
                .components(new Components()
                        .addParameters("myCustomHeader", new Parameter().in("header").schema(new StringSchema()).required(true).description("myCustomHeader").name("myCustomHeader")))
                .info(new Info()
                        .title("My Rest Application")
                        .version("1.2.26"));
    }
}

然而,swagger UI 没有在任何 API 中显示所需的参数。有人可以帮助我做错什么吗?

将参数定义添加到自定义 OpenAPI bean 将不起作用,因为该参数不会传播到操作定义。您可以使用 OperationCustomizer:

来实现您的目标
    @Bean
    public OperationCustomizer customize() {
        return (operation, handlerMethod) -> operation.addParametersItem(
                new Parameter()
                        .in("header")
                        .required(true)
                        .description("myCustomHeader")
                        .name("myCustomHeader"));
    }

springdoc-openapi 1.2.22引入了OperationCustomizer接口。在以前的版本中,您需要使用 OpenApiCustomiser:

@Component
public class MyOpenApiCustomizer implements OpenApiCustomiser {

    private static final List<Function<PathItem, Operation>> OPERATION_GETTERS = Arrays.asList(
            PathItem::getGet, PathItem::getPost, PathItem::getDelete, PathItem::getHead,
            PathItem::getOptions, PathItem::getPatch, PathItem::getPut);

    private Stream<Operation> getOperations(PathItem pathItem) {
        return OPERATION_GETTERS.stream()
                .map(getter -> getter.apply(pathItem))
                .filter(Objects::nonNull);
    }

    @Override
    public void customise(OpenAPI openApi) {
        openApi.getPaths().values().stream()
                .flatMap(this::getOperations)
                .forEach(this::customize);
    }

    private void customize(Operation operation) {
        operation.addParametersItem(
                new Parameter()
                        .in("header")
                        .required(true)
                        .description("myCustomHeader")
                        .name("myCustomHeader"));
    }
}