繁体   English   中英

Spring 禁用 Swagger-ui 进行生产

[英]Spring Disable Swagger-ui for production

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

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

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

这可以通过在生产环境中阻止 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 禁止状态。

Okey @zpavel 很好的解决方案,谢谢。 我刚刚已经有了这样的 spring 安全配置,当我添加你的安全配置时,我收到错误“WebSecurityConfigurers 上的@Order 必须是唯一的。”,所以我添加到一个 class @Order(1) 和另一个 @Order(2 )。 不幸的是.antMatchers("/**/swagger-ui.html").denyAll(); 拒绝所有请求,即使那些不是 swagger 呼叫的人,我也不知道为什么。

但是我修改了您的解决方案,它对我有用:

@Value("${spring.profiles.active}")
private String activeProfile;

@Override
public void configure(HttpSecurity http) throws Exception {
    if(activeProfile.equals("prod")){
        http.authorizeRequests()
                .antMatchers("/something").permitAll()
                .antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources/**", "/configuration/**", "/swagger-ui.html", "/webjars/**").denyAll()
                .antMatchers("/something").permitAll()
                .anyRequest().authenticated();
    } else {
        http.authorizeRequests()
                .antMatchers("/something").permitAll()
                .antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources/**", "/configuration/**", "/swagger-ui.html", "/webjars/**").permitAll()
                .antMatchers("/something").permitAll() 
                .antMatchers("/something").permitAll()
                .anyRequest().authenticated();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM