아무거나

스프링부트에서 swagger사용시 크로스 도메인 이슈 본문

Java/Java

스프링부트에서 swagger사용시 크로스 도메인 이슈

전봉근 2018. 11. 20. 21:18
반응형

Client(=User) -> Web Server -> API Server 로 구성되어 있는 하나의 시스템에서 서버 설정에 따라 크로스 도메인 이슈가 발생하곤 한다. 그래서 java 소스상에 @Configuration을 선언하고 WebMvcConfigurerAdapter를 상속받아 오버라이딩하여 메소드를 작성하면 해당 이슈는 해결된다.


import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
            .allowedMethods("GET", "POST", "PUT", "DELETE");
    }

}




만약 swagger를 이용한다면 아래와 같이 addResourceHandlers 메소드를 오라이드하여 작동하지 않으면 404 not found가 표시 될 것이다. 해당 이슈는 WebMvcConfigurerAdapter를 상속받는 클래스에 addResourceHandlers를 오버라이드하여 작동시키면 된다.


import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
            .allowedMethods("GET", "POST", "PUT", "DELETE");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
            .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/webjars/**")
            .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

}


반응형
Comments