简体   繁体   English

如何为 springdoc-openapi 端点调用添加 Header 授权

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

Swagger2 (springfox) worked with: 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: 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.我无法为 springdoc-openapi 实现它。 It seems the header is not working. header 似乎无法正常工作。

The behaviour you are describing is not related to springdoc-openapi.您描述的行为与 springdoc-openapi 无关。 But to swagger-ui which respects the OpenAPI Spec as well:但是对于同样尊重 OpenAPI 规范的 swagger-ui:

Adding parameter definition to a custom OpenAPI bean will not work because the parameter won't get propagated to the operations definitions.将参数定义添加到自定义 OpenAPI bean 将不起作用,因为参数不会传播到操作定义。 You can achieve your goal using OperationCustomizer:您可以使用 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.在 springdoc-openapi 1.2.22 中引入了 OperationCustomizer 接口。

For Authorization header to work, it is also required to have security in the root of the specification.要使Authorization header 工作,还需要在规范的根目录中具有security

For example, below code would set JWT bearer token in the Authorization header.例如,下面的代码将在Authorization header 中设置 JWT 不记名令牌。

@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 -生成的规范 yml 将如下 -

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

So, based on above specification, below part leads to Authorization header因此,基于上述规范,以下部分导致Authorization header

  security:
    - bearerAuth: []

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM