【问题标题】:How to add Header with Authorization for springdoc-openapi endpoint calls如何为 springdoc-openapi 端点调用添加带有授权的标头
【发布时间】:2020-09-17 11:50:41
【问题描述】:

Swagger2 (springfox) 与:

@Bean
public Docket getDocket() {
    return new Docket(DocumentationType.SWAGGER_2)
        .select()
        .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
        .apis(RequestHandlerSelectors.any())
        .paths(PathSelectors.any())
        .build()
        .useDefaultResponseMessages(false)
        .globalOperationParameters(Collections.singletonList(getAuthHeader()));
}

private Parameter getAuthHeader() {
    return new ParameterBuilder()
        .parameterType("header")
        .name("Authorization")
        .modelRef(new ModelRef("string"))
        .defaultValue(getBase64EncodedCredentials())
        .build();
}

private String getBase64EncodedCredentials() {
    String auth = authUser.getUser() + ":" + authUser.getPassword();
    byte[] encodedAuth = Base64.encode(auth.getBytes(StandardCharsets.UTF_8));
    return "Basic " + new String(encodedAuth, Charset.defaultCharset());
}

Springdoc-openapi:

@Bean
public OpenAPI getOpenAPI() {
    return new OpenAPI().components(new Components()
        .addHeaders("Authorization", new Header().description("Auth header").schema(new StringSchema()._default(getBase64EncodedCredentials()))));
}

我无法为 springdoc-openapi 实现它。标题似乎不起作用。

【问题讨论】:

  • 你知道了吗。我刚刚将 springdoc-openapi-ui 集成到一个 Spring Boot 应用程序中。但是虽然它可以为我的所有端点显示 swagger ui,但我没有选择为每个请求添加授权标头@akudama

标签: java spring-boot swagger-ui springdoc springdoc-openapi-ui


【解决方案1】:

您描述的行为与 springdoc-openapi 无关。但是对于同样尊重 OpenAPI 规范的 swagger-ui:

【讨论】:

    【解决方案2】:

    将参数定义添加到自定义 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 接口。

    【讨论】:

      猜你喜欢
      • 2020-09-24
      • 2019-03-30
      • 2016-03-24
      • 2021-03-29
      • 2019-11-14
      • 1970-01-01
      • 2017-11-24
      • 2020-11-07
      • 1970-01-01
      相关资源
      最近更新 更多