为了禁止访问Swagger UI页面,在Spring MVC中可以采取以下步骤:

  1. 在Spring MVC的配置文件中,添加以下代码来禁止对Swagger UI页面的访问:
@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/swagger-ui.html")
                .setCachePeriod(0)
                .addResourceLocations("classpath:/META-INF/resources/");
    }
}

这段代码将Swagger UI页面的访问路径设置为“/swagger-ui.html”,并将其映射到“classpath:/META-INF/resources/”目录下。同时还设置了缓存时间为0,以确保每次访问时都从磁盘上加载最新的资源。

  1. 禁止Swagger UI页面的访问还可以通过配置Spring Security来实现。在Spring Security的配置文件中,添加以下代码:
@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()
                .antMatchers("/v2/api-docs").permitAll()
                .anyRequest().authenticated()
                .and().httpBasic();
    }
}

这段代码将对Swagger UI页面的访问进行拒绝,并允许对Swagger资源和API文档的访问。同时,还对所有其他请求进行身份验证,以确保只有经过身份验证的用户才能访问应用程序的其他功能。


原文地址: https://www.cveoy.top/t/topic/zbo 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录