代码之家  ›  专栏  ›  技术社区  ›  Rumid

如何使用webflux处理springboot2中的HTTP选项请求?

  •  1
  • Rumid  · 技术社区  · 6 年前

    我将cors配置如下:

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

    @Bean
    RouterFunction<ServerResponse> routes() {
        return route(POST("/create")
                              .and(accept(APPLICATION_JSON))
                              .and(contentType(APPLICATION_JSON)), serverRequest 
                                     -> create(serverRequest);
    }
    

    无论如何,在我添加如下选项之前,我的angular应用程序无法发出任何请求:

    @Bean
    RouterFunction<ServerResponse> routes() {
        return route(POST("/create")
                              .and(accept(APPLICATION_JSON))
                              .and(contentType(APPLICATION_JSON)), serverRequest 
                                     -> create(serverRequest)
             .andRoute(OPTIONS("/create"), serverRequest -> ServerResponse.ok().build());
    }
    

    有必要吗?有没有办法去掉这个选项?

    3 回复  |  直到 6 年前
        1
  •  2
  •   Brian Clozel    6 年前

    我不认为WebFlux函数端点支持这一点。这个 Spring Framework reference documentation points to the CorsWebFilter instead .

    粗滤器 @Bean 并使用自定义 CorsConfiguration

        2
  •  1
  •   Huy Nguyen    6 年前

    这取决于。

    不需要支持选项。

    所有最新的现代浏览器都是通过发送HTTP选项来检查CORS来实现的。 如果您的服务器拒绝或拒绝它,浏览器将禁止您的请求。

        3
  •  1
  •   kj007 XdebugX    6 年前

    选项请求是跨来源资源共享(CORS)中的飞行前请求,需要它们跨不同来源发出请求。

    这个飞行前的请求是由一些浏览器作为一种安全措施来执行的,以确保正在执行的请求受到服务器的信任,即服务器理解请求中发送的方法、来源和头是安全的。

    这就是流程的工作原理:

    1. 客户端使用选项向服务器发送请求

    您可能还需要公开头文件。

    @Bean
        WebFluxConfigurer corsConfigurer() {
            return new WebFluxConfigurerComposite() {
    
                @Override
                public void addCorsMappings(CorsRegistry registry) {
                    registry.addMapping("/**").allowedOrigins("*")
                            .allowedMethods("*")
                    .exposedHeaders("*");
                }
            };
        }
    
        4
  •  0
  •   Brachi    5 年前

    我对通过“addCorsMappings”添加CORS也有同样的问题(就像你做的那样)

    @Bean
    CorsWebFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("http://domain1.com");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
    
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
    
        return new CorsWebFilter(source);
    }