Athomas
Athomas

Reputation: 573

Disabling Swagger with Spring MVC

I am using Swagger with Spring MVC. I would like to selectively disable swagger in specific environments (like Production). How can I do that?

Upvotes: 18

Views: 24869

Answers (3)

Dilip Krishnan
Dilip Krishnan

Reputation: 5487

In case you're using 1.x version of springfox formerly swagger-springmvc

When you configure your swagger spring-mvc plugin you can use the enable method to which you can pass in a boolean based on environment/profile etc.

@Bean 
public SwaggerSpringMvcPlugin customImplementation(){
    return new SwaggerSpringMvcPlugin(this.springSwaggerConfig)
        .apiInfo(apiInfo())
        .enable(environmentSpeficicBooleanFlag) //<--- Flag to enable or disable possibly loaded using a property file
        .includePatterns(".*pet.*");
}

Another way to do it is using spring profiles

@Bean
@Profile("production")
public SwaggerSpringMvcPlugin customImplementation(){
    return new SwaggerSpringMvcPlugin(this.springSwaggerConfig)
        .apiInfo(apiInfo())
        .enable(false) //<--- Flag set to false in the production profile
        .includePatterns(".*pet.*");
}

In case you're using 2.x version of springfox

When you configure your swagger spring-mvc plugin you can use the enable method to which you can pass in a boolean based on environment/profile etc.

@Bean 
public Docket customImplementation(){
    return new Docket(SWAGGER_2)
        .apiInfo(apiInfo())
        .enable(environmentSpeficicBooleanFlag) //<--- Flag to enable or disable possibly loaded using a property file
        .includePatterns(".*pet.*");
}

Another way to do it is using spring profiles

@Bean
@Profile("production")
public Docket customImplementation(){
    return new Docket(SWAGGER_2)
        .apiInfo(apiInfo())
        .enable(false) //<--- Flag set to false in the production profile
        .includePatterns(".*pet.*");
}

Upvotes: 44

jack
jack

Reputation: 113

You try this way

@Configuration
@EnableSwagger
// Loads the spring beans required by the framework
public class MySwaggerConfig
{

    private SpringSwaggerConfig springSwaggerConfig;

    /**
     * Required to autowire SpringSwaggerConfig
     */
    @Autowired
    public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig)
    {
        this.springSwaggerConfig = springSwaggerConfig;
    }

    /**
     * Every SwaggerSpringMvcPlugin bean is picked up by the swagger-mvc
     * framework - allowing for multiple swagger groups i.e. same code base
     * multiple swagger resource listings.
     */
    @Bean
    public SwaggerSpringMvcPlugin customImplementation()
    {
        return new SwaggerSpringMvcPlugin(this.springSwaggerConfig).apiInfo(apiInfo()).includePatterns(
                ".*?");
    }

    private ApiInfo apiInfo()
    {
        ApiInfo apiInfo = new ApiInfo(
                "xx", 
                "xxxx",
                "My Apps API terms of service", 
                "xxx",
                null,
                null);
        return apiInfo;
    }
}

pom is swagger-springmvc. veriosn is 0.9.5,

start server after request http://localhost:8080/appName/api-docs

Upvotes: -3

Custard
Custard

Reputation: 786

Dilip's answer is what you've asked for (I haven't tested it yet). But I have an additional scenario to deal with that may be of interest: on a public test box, I want the documentation to be enabled but private.

I've added the following to my WebMvcConfigurerAdapter which adds Basic Auth

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new SwaggerInterceptor())
            .addPathPatterns("/api-docs");
}

private class SwaggerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!authHeaderValid(request.getHeader("Authorization"))) {
            response.addHeader("Access-Control-Allow-Origin", "null");
            response.addHeader("WWW-Authenticate", "Basic realm=\"\"");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().println("HTTP Status " + HttpServletResponse.SC_UNAUTHORIZED);

            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { }

    private boolean authHeaderValid(String authorization) {
        if (authorization != null && authorization.startsWith("Basic ")) {
            final String[] values = new String(Base64.getDecoder().decode(authorization.substring("Basic ".length()))).split(":");

            return values[0].equals("username") && values[1].equals("password");
        }

        return false;
    }
}

Upvotes: 3

Related Questions