it-source

Spring Boot Swagger UI - UI 액세스 보호

criticalcode 2023. 7. 5. 20:47
반응형

Spring Boot Swagger UI - UI 액세스 보호

코드에 다음 클래스를 추가하여 기존 Springboot REST API에 간단한 스웨거 UI를 추가했습니다.

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

저의 문제는 API는 공개되어야 하지만, swagger docs는 공개되어서는 안 된다는 것입니다.저는 스웨거 문서에 인증을 요청하는 방법을 알고 싶은데, 이를 달성하는 간단한 방법을 아는 사람이 있나요?

구글 검색을 해봤는데 OAth 자료밖에 안 나오던데 이건 스웨거 문서가 아니라 엔드포인트에 대한 인증입니다...

Swagger 문서는 Swagger가 스프링 부트 애플리케이션과 통합되면 /v2/api-docs 엔드포인트에서 사용할 수 있습니다.

리소스를 보호하기 위해 스프링 보안을 사용하고 문서에 액세스하는 엔드포인트를 제한합니다.

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

보안 구성: 엔드포인트에 대한 액세스를 사용자에게만 제한합니다.

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

또한 요구 사항에 따라 swagger-ui.html도 보호할 수 있습니다.

대안적인 해결책이 있습니다.이것은 개발/QA 환경에서만 스웨거에 대한 액세스를 제한하는 것에 관한 것입니다.프로덕션 환경에서는 Swagger에 액세스할 수 없습니다.속성을 사용하고 있습니다(prop.swagger.enabled)는 개발/QA 환경에서만 Swagger-ui에 대한 스프링 보안 인증을 무시하기 위한 플래그입니다.

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

이 보일러 플래터를 사용하여 스웨거를 구성하고 고정합니다.

@Configuration
@EnableSwagger2
public class SwaggerConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any()).build();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
        .antMatchers("/v2/api-docs",
                "/configuration/ui",
                "/swagger-resources/**",
                "/configuration/security",
                "/swagger-ui.html",
                "/webjars/**")
        .authenticated().and().httpBasic();

    }

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

}

언급URL : https://stackoverflow.com/questions/45766296/spring-boot-swagger-ui-protect-ui-access

반응형