refactor: knife4j 全局设置参数排除无需鉴权的接口
This commit is contained in:
@@ -5,9 +5,12 @@ 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 lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springdoc.core.customizers.GlobalOpenApiCustomizer;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
|
||||
/**
|
||||
@@ -19,19 +22,26 @@ import org.springframework.http.HttpHeaders;
|
||||
* @since 2023/2/17
|
||||
*/
|
||||
@Configuration
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class SwaggerConfig {
|
||||
|
||||
private final Environment environment;
|
||||
|
||||
/**
|
||||
* 接口信息
|
||||
*/
|
||||
@Bean
|
||||
public OpenAPI openApi() {
|
||||
|
||||
String appVersion = environment.getProperty("project.version", "1.0.0");
|
||||
|
||||
return new OpenAPI()
|
||||
.info(new Info()
|
||||
.title("系统接口文档")
|
||||
.version("2.4.0")
|
||||
.version(appVersion)
|
||||
)
|
||||
// 全局安全校验项,也可以在对应的controller上加注解SecurityRequirement
|
||||
// 配置全局鉴权参数-Authorize
|
||||
.components(new Components()
|
||||
.addSecuritySchemes(HttpHeaders.AUTHORIZATION,
|
||||
new SecurityScheme()
|
||||
@@ -41,17 +51,34 @@ public class SwaggerConfig {
|
||||
.scheme("Bearer")
|
||||
.bearerFormat("JWT")
|
||||
)
|
||||
)
|
||||
.addSecurityItem(new SecurityRequirement().addList(HttpHeaders.AUTHORIZATION)) ;
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 全局自定义扩展
|
||||
* <p>
|
||||
* 在OpenAPI规范中,Operation 是一个表示 API 端点(Endpoint)或操作的对象。
|
||||
* 每个路径(Path)对象可以包含一个或多个 Operation 对象,用于描述与该路径相关联的不同 HTTP 方法(例如 GET、POST、PUT 等)。
|
||||
*/
|
||||
@Bean
|
||||
public GlobalOpenApiCustomizer globalOpenApiCustomizer() {
|
||||
return openApi -> openApi.getPaths().values()
|
||||
.stream()
|
||||
.flatMap(pathItem -> pathItem.readOperations().stream())
|
||||
.forEach(operation -> operation.security(openApi.getSecurity()));
|
||||
return openApi -> {
|
||||
// 全局添加鉴权参数
|
||||
if (openApi.getPaths() != null) {
|
||||
openApi.getPaths().forEach((s, pathItem) -> {
|
||||
// 登录接口/验证码不需要添加鉴权参数
|
||||
if (s.equals("/api/v1/auth/login") || s.equals("/api/v1/auth/captcha")) {
|
||||
return;
|
||||
}
|
||||
// 接口添加鉴权参数
|
||||
pathItem.readOperations()
|
||||
.forEach(operation ->
|
||||
operation.addSecurityItem(new SecurityRequirement().addList(HttpHeaders.AUTHORIZATION))
|
||||
);
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user