java—springdoc openapi ui中的启用授权按钮,用于承载令牌身份验证(jwt)

zte4gxcn  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(956)

如何在springdoc openapi ui(openapi 3.0)中启用“授权”按钮 /swagger-ui.html )对于承载令牌身份验证,例如jwt。
spring需要添加哪些注解 @Controller 以及 @Configuration 上课?

eqfvzcg8

eqfvzcg81#

我更喜欢使用bean初始化而不是注解。

@Configuration
public class OpenApi30Config {

  private final String moduleName;
  private final String apiVersion;

  public OpenApi30Config(
      @Value("${module-name}") String moduleName,
      @Value("${api-version}") String apiVersion) {
    this.moduleName = moduleName;
    this.apiVersion = apiVersion;
  }

  @Bean
  public OpenAPI customOpenAPI() {
    final String securitySchemeName = "bearerAuth";
    final String apiTitle = String.format("%s API", StringUtils.capitalize(moduleName));
    return new OpenAPI()
        .addSecurityItem(new SecurityRequirement().addList(securitySchemeName))
        .components(
            new Components()
                .addSecuritySchemes(securitySchemeName,
                    new SecurityScheme()
                        .name(securitySchemeName)
                        .type(SecurityScheme.Type.HTTP)
                        .scheme("bearer")
                        .bearerFormat("JWT")
                )
        )
        .info(new Info().title(apiTitle).version(apiVersion));
  }
}

代码行

.addSecurityItem(new SecurityRequirement().addList(securitySchemeName))

允许添加全局安全性架构,并避免将安全性写入方法的每个@操作。

wj8zmpe1

wj8zmpe12#

使用注解定义openapi 3.0的全局安全方案 @io.swagger.v3.oas.annotations.security.SecurityScheme 在一个 @Configuration 豆子:

@Configuration
@OpenAPIDefinition(info = @Info(title = "My API", version = "v1"))
@SecurityScheme(
    name = "bearerAuth",
    type = SecuritySchemeType.HTTP,
    bearerFormat = "JWT",
    scheme = "bearer"
)
public class OpenApi30Config {

}

注解每个 @RestController 需要承载令牌身份验证(jwt)的方法 @io.swagger.v3.oas.annotations.Operation 引用已定义的安全方案:

@Operation(summary = "My endpoint", security = @SecurityRequirement(name = "bearerAuth"))

相关问题