在Spring Boot中禁止访问Swagger UI页面并在拦截器中进行拦截可以通过配置Spring Security来实现。下面是一个简单的示例,演示如何实现这一点:
在Spring Boot项目中创建一个Spring Security配置类,如下所示:
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/swagger-ui.html").denyAll()
.antMatchers("/swagger-resources/**").permitAll() // 如果需要访问Swagger的其他资源,可以放行
.and()
.csrf().disable();
}
}
在这个配置中,我们使用HttpSecurity
对象配置了访问规则。.antMatchers("/swagger-ui.html").denyAll()
表示禁止访问 swagger-ui.html
页面,而 .antMatchers("/swagger-resources/**").permitAll()
则允许访问Swagger的其他资源。
接下来,创建一个拦截器(Interceptor)类,用于拦截对 swagger-ui.html
的访问:
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (request.getRequestURI().equals("/swagger-ui.html")) {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
return false; // 拦截访问
}
return true; // 放行其他请求
}
// 可以实现 postHandle 和 afterCompletion 方法进行相应处理
}
配置这个拦截器类并使其生效:
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor());
}
}
这样配置后,即可通过Spring Security和拦截器实现禁止访问Swagger UI页面 swagger-ui.html
。
如果你想完全禁用 Swagger UI 和 Swagger 资源,你可以在 Spring Boot 项目的 application.yml
或 application.properties
文件中添加以下配置来实现:
在 application.yml
文件中的配置:
spring:
profiles:
swagger:
enabled: false
在 application.properties
文件中的配置:
spring.profiles.swagger.enabled=false
通过将这些配置设置为 false
,你可以完全禁用 Spring Boot 中关于 Swagger UI 和 Swagger 资源的自动配置和展示。这样就可以确保这些端点和页面对外部用户不可见或无法访问。