SpringBoot整合Swagger页面禁止访问swagger-ui.html方式,
分享于 点击 41476 次 点评:181
SpringBoot整合Swagger页面禁止访问swagger-ui.html方式,
目录
- SpringBoot整合Swagger页面禁止访问swagger-ui.html
- 在Spring Boot项目中创建一个Spring Security配置类
- 创建一个拦截器(Interceptor)类
- 如果你想完全禁用Swagger UI和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 资源的自动配置和展示。
这样就可以确保这些端点和页面对外部用户不可见或无法访问。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持3672js教程。
您可能感兴趣的文章:- Springboot整合Swagger2后访问swagger-ui.html 404报错问题解决方案
- Springboot下swagger-ui.html访问不到的解决方案
- SpringBoot3整合Swagger3时出现Type javax.servlet.http.H的ttpServletRequest not present错误解决方法
- SpringBoot3集成swagger文档的使用方法
- SpringBoot和Springfox(Swagger)版本不兼容的解决方案
用户点评