Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot Swagger UI - Protect UI Access

I added a simple swagger UI to my existing springboot REST API by adding the following class to my code:

@EnableSwagger2
@Configuration
public class SwaggerConfig {                                    
    @Bean
    public Docket api() { 
        return new Docket(DocumentationType.SWAGGER_2)  
            .select()
            .paths(PathSelectors.regex("/v1.*"))
            .build()
            .pathMapping("/")
            .apiInfo(metadata());
    }


    private ApiInfo metadata() {
        return new ApiInfoBuilder()
          .title("My awesome API")
          .description("Some description")
          .version("1.0")
          .build();
      }
}

My problem is that the API should be public, but the swagger docs should not. I would like a way of requesting authentication to the swagger documentation, anyone knows any simple way of achieving this?

I tried to google it but I could only find OAth stuff, but this is authentication for the endpoints not the swagger documentation...

like image 373
Ernani Avatar asked Aug 18 '17 23:08

Ernani


People also ask

How to configure Spring Security with Swagger UI?

Start the project using Swagger UI if we do not try to test the REST endpoints it asks for the username and password. If we enter these, Swagger is able to successfully interact with the endpoints. Let us now configure Swagger for Spring Security. In the SwaggerSpringDemoApplication class, specify SecurityScheme.

How do I disable Swagger in Spring Boot?

To disable Swagger in production, let's toggle whether this configuration bean is injected. 3. Using Spring Profiles In Spring, we can use the @Profile annotation to enable or disable the injection of beans. Let's try using a SpEL expression to match the “swagger” profile, but not the “prod” profile:

What is Swagger-UI and Springfox-boot-starter dependency?

“ springfox-boot-starter ” dependency is used to generate API docs. “ swagger-ui ” is used to display this documentation in pretty way and also it provides interaction between users and API endpoints on the browser. After adding dependencies to pom.xml, a Configuration class must be added to project as seen below.

What is websecurityconfigureradapter in Spring Boot?

Also we extend WebSecurityConfigurerAdapter, which provides us a configuration methods,to define rules to specify what URIs to protect or pass through. Extending WebSecurityConfiguration allows to customize spring security by overriding methods.


2 Answers

Swagger docs will be available at /v2/api-docs endpoint when swagger integrated with spring boot application.

Inorder to protect the resource , make use of spring security and restrict the endpoint for accessing the docs

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

Security configuration : restricting access to the endpoint only to the users

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()               
                .antMatchers("/v2/api-docs").authenticated()
                .and()
                .httpBasic();

    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER");
    }
}

Additionally, swagger-ui.html can also be secured based on the requirement.

like image 190
Barath Avatar answered Oct 13 '22 00:10

Barath


Here's a an alternative solution. This is about limiting access to swagger only in development/qa environment. The production environment will not have access to Swagger. I am using a property (prop.swagger.enabled) as a flag to bypass spring security authentication for swagger-ui only in development/qa environment.

@Configuration
@EnableSwagger2
public class SwaggerConfiguration extends WebSecurityConfigurerAdapter implements WebMvcConfigurer {

@Value("${prop.swagger.enabled:false}")
private boolean enableSwagger;

@Bean
public Docket SwaggerConfig() {
    return new Docket(DocumentationType.SWAGGER_2)
            .enable(enableSwagger)
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.your.controller"))
            .paths(PathSelectors.any())
            .build();
}

@Override
public void configure(WebSecurity web) throws Exception {
    if (enableSwagger)  
        web.ignoring().antMatchers("/v2/api-docs",
                               "/configuration/ui",
                               "/swagger-resources/**",
                               "/configuration/security",
                               "/swagger-ui.html",
                               "/webjars/**");
}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    if (enableSwagger) {
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
  }
}
like image 39
Abdul Rahman Avatar answered Oct 13 '22 00:10

Abdul Rahman