5

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 实现它。似乎标题不起作用。

4

2 回答 2

5

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

于 2020-05-30T13:27:38.993 回答
1

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

于 2021-10-21T06:28:13.430 回答