如何为springdoc-openapi端点调用添加带有授权的标头

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

How to add Header with Authorization for springdoc-openapi endpoint calls

问题

**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中实现它似乎header部分无法正常工作
英文:

Swagger2 (springfox) worked with:

@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()))));
}

I cant achieve it for springdoc-openapi. It seems the header is not working.

答案1

得分: 11

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

@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 中引入的。

英文:

Adding parameter definition to a custom OpenAPI bean will not work because the parameter won't get propagated to the operations definitions. You can achieve your goal using OperationCustomizer:

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

The OperationCustomizer interface was introduced in the springdoc-openapi 1.2.22.

答案2

得分: 9

你所描述的行为与 springdoc-openapi 无关,而与遵循 OpenAPI 规范的 swagger-ui 有关:

OpenAPI 3 规范不允许显式添加 Authorization header。欲了解更多信息,请阅读:

注意:不允许使用 Accept、Content-Type 和 Authorization 等名称的头部参数。要描述这些头部参数,请参阅

请阅读:

英文:

The behaviour you are describing is not related to springdoc-openapi. But to swagger-ui which respects the OpenAPI Spec as well:

The OpenAPI 3 specification does not allow explicitly adding Authorization header. For more information, please read:

Note: Header parameters named Accept, Content-Type and Authorization are not allowed. To describe these headers

Please read:

答案3

得分: 9

关于 Authorization 头部的使用,还需要在规范的根部分拥有 security 部分。

例如,下面的代码将在 Authorization 头部中设置 JWT Bearer 令牌。

@Bean
public OpenAPI customOpenAPI(@Value("${openapi.service.title}") String serviceTitle, @Value("${openapi.service.version}") String serviceVersion) {
    final String securitySchemeName = "bearerAuth";
    return new OpenAPI()
            .components(
                    new Components()
                            .addSecuritySchemes(securitySchemeName,
                                    new SecurityScheme()
                                            .type(SecurityScheme.Type.HTTP)
                                            .scheme("bearer")
                                            .bearerFormat("JWT")
                            )
            )
            .security(List.of(new SecurityRequirement().addList(securitySchemeName)))
            .info(new Info().title(serviceTitle).version(serviceVersion));
}

生成的规范 YAML 如下所示:

security:
  - bearerAuth: []
...
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT

因此,根据上述规范,以下部分涉及到 Authorization 头部:

security:
  - bearerAuth: []
英文:

For Authorization header to work, it is also required to have security in the root of the specification.

For example, below code would set JWT bearer token in the Authorization header.

@Bean
public OpenAPI customOpenAPI(@Value("${openapi.service.title}") String serviceTitle, @Value("${openapi.service.version}") String serviceVersion) {
final String securitySchemeName = "bearerAuth";
return new OpenAPI()
.components(
new Components()
.addSecuritySchemes(securitySchemeName,
new SecurityScheme()
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")
.bearerFormat("JWT")
)
)
.security(List.of(new SecurityRequirement().addList(securitySchemeName)))
.info(new Info().title(serviceTitle).version(serviceVersion));
}

Generated specification yml will be as below -

security:
- bearerAuth: []
...
components:
securitySchemes:
bearerAuth:
type: http
scheme: bearer
bearerFormat: JWT

So, based on above specification, below part leads to Authorization header

  security:
- bearerAuth: []

huangapple
  • 本文由 发表于 2020年5月30日 04:10:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/62093928.html
匿名

发表评论

匿名网友

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

确定