SpringBoot integrates Swagger pages forbidden access
Disable access to Swagger UI pages in Spring Boot and intercepting in the interceptor can be achieved by configuring Spring Security.
Here is a simple example that demonstrates how to achieve this:
Create a Spring Security configuration class in a Spring Boot project
As shown below:
import ; import ; import ; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { () .antMatchers("/").denyAll() .antMatchers("/swagger-resources/**").permitAll() // If you need to access other resources of Swagger, you can release it .and() .csrf().disable(); } }
In this configuration, we useHttpSecurity
The object has access rules configured.
-
.antMatchers("/").denyAll()
Indicates that access is prohibitedpage
- and
.antMatchers("/swagger-resources/**").permitAll()
Allow access to other resources of Swagger
Create an Interceptor class
Used to intercept pairsVisits:
import ; import ; import ; import ; public class MyInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (().equals("/")) { (HttpServletResponse.SC_FORBIDDEN); return false; // Intercept access } return true; // Release other requests } // Can implement postHandle and afterCompletion methods for corresponding processing}
Configure this interceptor class and make it effective:
import ; import ; @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { (new MyInterceptor()); } }
After this configuration, you can use Spring Security and interceptor to prohibit access to Swagger UI pages.。
If you want to completely disable Swagger UI and Swagger resources
You can do it in the Spring Boot projector
Add the following configuration to the file to implement it:
- exist
Configuration in the file:
spring: profiles: swagger: enabled: false
- exist
Configuration in the file:
=false
By setting these configurations tofalse
, you can completely disable the automatic configuration and presentation of Swagger UI and Swagger resources in Spring Boot.
This ensures that these endpoints and pages are not visible or accessible to external users.
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.