복붙노트

[SPRING] Spring 5 Webflux에서 CORS를 사용 하시겠습니까?

SPRING

Spring 5 Webflux에서 CORS를 사용 하시겠습니까?

Spring 5 Webflux 프로젝트에서 CORS를 사용하려면 어떻게해야합니까?

적절한 문서를 찾을 수 없습니다.

해결법

  1. ==============================

    1.이 맞춤 필터로 성공했습니다.

    이 맞춤 필터로 성공했습니다.

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.http.HttpHeaders;
    import org.springframework.http.HttpMethod;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.server.reactive.ServerHttpRequest;
    import org.springframework.http.server.reactive.ServerHttpResponse;
    import org.springframework.web.cors.reactive.CorsUtils;
    import org.springframework.web.server.ServerWebExchange;
    import org.springframework.web.server.WebFilter;
    import org.springframework.web.server.WebFilterChain;
    
    import reactor.core.publisher.Mono;
    
    
    @Configuration
    public class CorsConfiguration {
    
      private static final String ALLOWED_HEADERS = "x-requested-with, authorization, Content-Type, Authorization, credential, X-XSRF-TOKEN";
      private static final String ALLOWED_METHODS = "GET, PUT, POST, DELETE, OPTIONS";
      private static final String ALLOWED_ORIGIN = "*";
      private static final String MAX_AGE = "3600";
    
      @Bean
      public WebFilter corsFilter() {
        return (ServerWebExchange ctx, WebFilterChain chain) -> {
          ServerHttpRequest request = ctx.getRequest();
          if (CorsUtils.isCorsRequest(request)) {
            ServerHttpResponse response = ctx.getResponse();
            HttpHeaders headers = response.getHeaders();
            headers.add("Access-Control-Allow-Origin", ALLOWED_ORIGIN);
            headers.add("Access-Control-Allow-Methods", ALLOWED_METHODS);
            headers.add("Access-Control-Max-Age", MAX_AGE);
            headers.add("Access-Control-Allow-Headers",ALLOWED_HEADERS);
            if (request.getMethod() == HttpMethod.OPTIONS) {
              response.setStatusCode(HttpStatus.OK);
              return Mono.empty();
            }
          }
          return chain.filter(ctx);
        };
      }
    
    }
    

    org.springframework.boot : spring-boot-starter-web은 종속성으로 포함되면 안됩니다. 필터가 작동하지 않습니다.

  2. ==============================

    2.

    @Configuration
    public class WebFluxConfig {
    
        @Bean
        public WebFluxConfigurer corsConfigurer() {
            return new WebFluxConfigurerComposite() {
    
                @Override
                public void addCorsMappings(CorsRegistry registry) {
                    registry.addMapping("/**").allowedOrigins("*")
                            .allowedMethods("*");
                }
            };
        }
    }
    

    이는 다음에 해당합니다 :

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
    
            @Override
            public void addCorsMappings(CorsRegistry registry) {
    

    봄에 대한 mvc.

  3. ==============================

    3.Webflux Configurer의 또 다른 솔루션은 다음과 같습니다.

    Webflux Configurer의 또 다른 솔루션은 다음과 같습니다.

    사이드 노트 : Kotlin 코드 (프로젝트에서 복사 한 것)가 있지만 Java 코드로 쉽게 변환 할 수 있습니다.

    @Configuration
    @EnableWebFlux
    class WebConfig: WebFluxConfigurer
    {
        override fun addCorsMappings(registry: CorsRegistry)
        {
            registry.addMapping("/**")
                .allowedOrigins("*") // any host or put domain(s) here
                .allowedMethods("GET, POST") // put the http verbs you want allow
                .allowedHeaders("Authorization") // put the http headers you want allow
        }
    }
    
  4. ==============================

    4.@Dachstein 덕분에 WebMvc configs를 Webflux로 바꾸는 것이 여기에서 전역 CORS Config를 추가하는 올바른 방법입니다.

    @Dachstein 덕분에 WebMvc configs를 Webflux로 바꾸는 것이 여기에서 전역 CORS Config를 추가하는 올바른 방법입니다.

    @Configuration
    @EnableWebFlux
    public class CORSConfig implements WebFluxConfigurer {
    
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedMethods("*");
        }
    }
    
  5. ==============================

    5.다음은 공식 문서 링크입니다.

    다음은 공식 문서 링크입니다.

    https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html#webflux-cors

    3 가지 주요 옵션이 있습니다.

    1) @CrossOrigin 주석을 나머지 컨트롤러에서 사용 - 클래스 및 / 또는 메서드 수준에서 사용할 수 있습니다.

    2) WebFluxConfigurer에서 addCorsMapping 메소드 구현 - 글로벌 CorsRegistry 객체에 대한 접근을 제공합니다.

    3) CorsWebFilter 구성 요소 정의 - 기능 끝점에 대한 좋은 선택

    문서를 보시고, 잘 설명되어 있습니다.

    개인적으로는 개발 중에 cors를 허용하고 프론트 엔드 모듈에서 백엔드를 분리 할 때 세 번째 옵션을 사용합니다.

    백엔드 모듈에 webflux가 있고 프론트 엔드에 반응 또는 각진 응용 프로그램이 있다고 상상해보십시오. 프론트 엔드 기능을 개발하는 동안 netpack에서 백엔드를 계속 실행하면서 hot reloading을 위해 webpack-dev-server를 사용하려고 할 수 있습니다. 포트가 다르면 CORS 문제가 발생할 수 있습니다. 세 번째 옵션을 사용하면 @Component를 @Profile ( "dev")에 쉽게 연결할 수 있으므로 prod에 배포 할 때 CORS가 활성화됩니다.

  6. from https://stackoverflow.com/questions/46978794/enable-cors-in-spring-5-webflux by cc-by-sa and MIT license