Enable Authorize button in springdoc-openapi-ui for Bearer Token Authentication (JWT)
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.
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"))