首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >openapi 3.0中所有API的强制标头

openapi 3.0中所有API的强制标头
EN

Stack Overflow用户
提问于 2020-01-30 16:24:49
回答 1查看 3.9K关注 0票数 2

我使用的是带有Spring-boot5的YAML3.0,因此没有配置OpenAPI。我有一个包含客户端标识ID的标头(这不是身份验证标头)。我想让它成为一个强制的头参数。在OpenAPI配置下添加

代码语言:javascript
运行
复制
@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中都不显示所需的参数。有人能帮我指出我哪里做错了吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-01-30 19:31:11

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

代码语言:javascript
运行
复制
    @Bean
    public OperationCustomizer customize() {
        return (operation, handlerMethod) -> operation.addParametersItem(
                new Parameter()
                        .in("header")
                        .required(true)
                        .description("myCustomHeader")
                        .name("myCustomHeader"));
    }

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

代码语言:javascript
运行
复制
@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"));
    }
}
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59981687

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档