SpringBoot整合Swagger页面禁止访问swagger-ui.html方式
作者:费曼乐园
本文介绍了如何在SpringBoot项目中通过配置SpringSecurity和创建拦截器来禁止访问SwaggerUI页面,此外,还提供了禁用SwaggerUI和Swagger资源的配置方法,以确保这些端点和页面对外部用户不可见或无法访问
SpringBoot整合Swagger页面禁止访问swagger-ui.html
在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 资源的自动配置和展示。
这样就可以确保这些端点和页面对外部用户不可见或无法访问。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
