在 springdoc-openapi-ui 中启用授权按钮以进行持有者令牌身份验证 (JWT)

2022-09-01 01:43:56

如何在spredoc-openapi-ui(OpenAPI 3.0)中为持有者令牌身份验证启用“授权”按钮,例如JWT。/swagger-ui.html

必须向 Spring 和类添加哪些注释?@Controller@Configuration

Authorize button

Authorize form for Bearer Token Authentication


答案 1

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

import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info; 
import io.swagger.v3.oas.models.security.SecurityRequirement; 
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

@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))

允许添加全局安全模式,并摆脱对每个@Operation方法的写入安全性。


答案 2

使用 Bean 中的注释为 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 {

}

通过引用定义的安全方案,对每个需要持有者令牌身份验证 (JWT) 的方法进行注释:@RestController@io.swagger.v3.oas.annotations.Operation

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