springboot项目关闭swagger防止漏洞扫描
在Spring Boot项目中禁用Swagger可以通过以下方式实现:
- 在
application.properties
或application.yml
配置文件中禁用Swagger。
# application.properties
springfox.documentation.enabled=false
或者
# application.yml
springfox:
documentation:
enabled: false
- 通过Java配置来禁用Swagger。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.data.rest.configuration.SpringDataRestConfiguration;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).enable(false).select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}
- 如果使用Spring Security,确保Swagger UI不需要认证即可访问。
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
.requestMatchers("/swagger-ui.html").permitAll()
.anyRequest().authenticated();
}
}
- 如果不希望任何人访问Swagger UI,可以移除Swagger相关的依赖。
在Maven的pom.xml
中移除:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
在Gradle的build.gradle
中移除:
dependencies {
implementation 'io.springfox:springfox-swagger2'
implementation 'io.springfox:springfox-swagger-ui'
}
以上方法可以有效禁用Swagger,防止安全漏洞扫描。
评论已关闭