首页 > 解决方案 > Spring禁用Swagger-ui进行生产

问题描述

我知道如何禁用 swagger 进行生产 - 我只需要在配置类中添加注释 @Profile("!prod") :

@Configuration
@EnableSwagger2
@RequiredArgsConstructor
@Profile("!prod")
public class SwaggerConfig {

添加注释 的结果但是结果是,swagger-ui.html 在浏览器中仍然可用,只是它是空的。我想知道有没有完全禁用它的解决方案,所以页面不会加载?

标签: javaspringswagger

解决方案


这可以通过阻止生产环境的 url 来简单地使用 spring-security 来完成。请试试 :

将依赖项(如果您使用的是 spring-boot)添加到 pom.xml :

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

添加配置文件:

@Configuration
@Profile("prod")
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/**/swagger-ui.html").denyAll();
    }
}

它将发送 403 禁止状态。


推荐阅读