问题
How to enable "Authorize" button in springdoc-openapi-ui (OpenAPI 3.0 /swagger-ui.html
) for Bearer Token Authentication, for example JWT.
What annotations have to be added to Spring @Controller
and @Configuration
classes?
回答1:
Define a global security scheme for OpenAPI 3.0 using annotation @io.swagger.v3.oas.annotations.security.SecurityScheme
in a @Configuration
bean:
@Configuration
@OpenAPIDefinition(info = @Info(title = "My API", version = "v1"))
@SecurityScheme(
name = "bearerAuth",
type = SecuritySchemeType.HTTP,
bearerFormat = "JWT",
scheme = "bearer"
)
public class OpenApi30Config {
}
Annotate each @RestController
method requiring Bearer Token Authentication (JWT) with @io.swagger.v3.oas.annotations.Operation
referencing the defined security scheme:
@Operation(summary = "My endpoint", security = @SecurityRequirement(name = "bearerAuth"))
回答2:
I prefer to use bean initialization instead of annotation.
@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));
}
}
The line of code
.addSecurityItem(new SecurityRequirement().addList(securitySchemeName))
allows to add global security schema and to get rid of writing security to each @Operation of method.
来源:https://stackoverflow.com/questions/59898874/enable-authorize-button-in-springdoc-openapi-ui-for-bearer-token-authentication