Piotr Filochowski
Piotr Filochowski

Reputation: 140

Spring Disable Swagger-ui for production

I know how to disable swagger for production - i only need to add annotation @Profile("!prod") in configuration class:

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

result of adding annotation But the result is, that the swagger-ui.html still is available in browser, only its empty. I wonder is there solution to disable it fully, so the page will not load?

Upvotes: 1

Views: 4948

Answers (2)

Piotr Filochowski
Piotr Filochowski

Reputation: 140

Okey @zpavel its good solution, thank you. I just already had such spring security configuration, and when i added yours, i got error "@Order on WebSecurityConfigurers must be unique.", so i added to one class @Order(1), and to the other one @Order(2). Unfortunately the .antMatchers("/**/swagger-ui.html").denyAll(); denied all request even those who were not swagger calls, i don't know why.

Hovewer i modified Your solution and it worked for me:

@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();
    }
}

Upvotes: 3

zpavel
zpavel

Reputation: 969

this could be simply done with spring-security by blocking the url for the production environment. Please try :

Add dependency (if you are using spring-boot) to pom.xml :

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

Add configuration file :

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

It will send 403 forbidden status.

Upvotes: 2

Related Questions