我已经开始新的
Spring Boot 3.1.3
。对于API文档,我遵循了官方的Springdocspringdoc-openapi v2.2.0
文档,一切都很好。然后我添加了一个新的空类来配置OpenAPI
,如下所示:
@OpenAPIDefinition(
info = @Info(
title = "Project API",
version = "v1",
description = "Project API reference for developers",
contact = @Contact(
name = "Test Project",
email = "[email protected]",
url = "https://developer.XXX.net"
)
),
servers = {
@Server(
url = "http://localhost:8080/",
description = "local"
),
@Server(
url = "https://api.stage.XXX.net/",
description = "Stage Server"
)
},
security = {
@SecurityRequirement(name = "bearerAuth")
}
)
@SecurityScheme(
name = "bearerAuth",
type = SecuritySchemeType.HTTP,
bearerFormat = "JWT",
scheme = "bearer",
description = "JWT token",
in = SecuritySchemeIn.HEADER
)
@Configuration
public class OpenApiConfig {
}
但是这些注释对
Swagger UI
没有任何影响。
OpenAPI
和 Swagger UI
配置 application.properties
:
springdoc.api-docs.enabled=true
springdoc.api-docs.path=/api-docs
springdoc.swagger-ui.enabled=true
springdoc.swagger-ui.path=/api-docs/swagger-ui.html
springdoc.show-actuator=false
springdoc.cache.disabled=true
还有我的
SecurityConfiguration
:
private final String[] openApiPaths = new String[]{
"/api-docs/**",
"/v2/api-docs",
"/v3/api-docs",
"v3/api-docs/**",
"/swagger-resources",
"/swagger-resources/**",
"/configuration/ui",
"/configuration/security",
"/swagger-ui.html",
"/swagger-ui/**",
"/webjars/**"
};
// ...
.authorizeHttpRequests(authorizeHttpRequests -> {
authorizeHttpRequests.requestMatchers(openApiPaths)
.permitAll();
authorizeHttpRequests.anyRequest()
.authenticated();
}
)
我用
@OpenAPIDefinition
将 @SecurityScheme
和 @SpringBootApplication
移至应用程序类,并且它有效:
@OpenAPIDefinition(
info = @Info(
title = "Project API",
version = "v1",
description = "Project API reference for developers",
contact = @Contact(
name = "Test Project",
email = "[email protected]",
url = "https://developer.XXX.net"
)
),
servers = {
@Server(
url = "http://localhost:8080/",
description = "local"
),
@Server(
url = "https://api.stage.XXX.net/",
description = "Stage Server"
)
},
security = {
@SecurityRequirement(name = "bearerAuth")
}
)
@SecurityScheme(
name = "bearerAuth",
type = SecuritySchemeType.HTTP,
bearerFormat = "JWT",
scheme = "bearer",
description = "JWT token",
in = SecuritySchemeIn.HEADER
)
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}