为什么我的 Spring 控制器不处理 GraphiQL 发送的 OPTIONS 请求?

Why does my Spring controller not handle an OPTIONS request sent by GraphiQL?

我正在尝试让 GraphQL Java server 与 GraphiQL 服务器一起工作。

在本地使用 GraphiQL 运行 我提交了一个包含以下参数的查询:

我的 Spring 控制器(从 here 复制)如下所示:

@Controller
@EnableAutoConfiguration
public class MavenController {
    private final MavenSchema schema = new MavenSchema();
    private final GraphQL graphql = new GraphQL(schema.getSchema());
    private static final Logger log = LoggerFactory.getLogger(MavenController.class);

    @RequestMapping(value = "/graphql", method = RequestMethod.OPTIONS, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Object executeOperation(@RequestBody Map body) {
        log.error("body: " + body);
        final String query = (String) body.get("query");
        final Map<String, Object> variables = (Map<String, Object>) body.get("variables");
        final ExecutionResult executionResult = graphql.execute(query, (Object) null, variables);
        final Map<String, Object> result = new LinkedHashMap<>();
        if (executionResult.getErrors().size() > 0) {
            result.put("errors", executionResult.getErrors());
            log.error("Errors: {}", executionResult.getErrors());
        }
        log.error("data: " + executionResult.getData());
        result.put("data", executionResult.getData());
        return result;
    }
}

理论上,当我在 GraphiQL 中提交查询时,应该调用 executeOperation。不是,我在控制台输出中没有看到日志语句。

我做错了什么?当在 GraphiQL 中提交查询时,如何确保调用 MavenController.executeOperation

更新 1 (13.01.2017 13:35 MSK): 这里有一个关于如何重现错误的教程。我的目标是创建一个基于 Java 的 GraphQL 服务器,我可以使用 GraphiQL 与之交互。如果可能,这应该在本地工作。

read为了做到这一点,需要以下步骤:

  1. Set up a GraphQL server. An example of this can be found here https://github.com/graphql-java/todomvc-relay-java. That example uses Spring Boot, but you can use whatever HTTP server you like to get that going.
  2. Set up the GraphiQL server. That is a bit beyond the scope of this project, but basically you need to get GraphiQL talking to the server in step 1 above. It will use introspection to load the schema.

我查看了项目 todomvc-relay-java, modified it according to my needs and put it into directory E:\graphiql-java\graphql-server. You can download an archive with that directory here

第 1 步:安装 Node.JS

步骤 2

转到 E:\graphiql-java\graphql-server\app 和 运行 npm install

步骤 3

运行 npm start 来自同一目录。

步骤 4

转到 E:\graphiql-java\graphql-server 和 运行 gradlew start

步骤 5

运行 docker run -p 8888:8080 -d -e GRAPHQL_SERVER=http://localhost:8080/graphql merapar/graphql-browser-docker.

Docker 来源:graphql-browser-docker

步骤 6

启动 Chrome 并禁用 XSS 检查,例如。 G。 "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --args --disable-xss-auditor。一些消息来源声称您必须杀死所有其他 Chrome 个实例才能使这些参数生效。

步骤 7

在该浏览器中打开 http://localhost:8888/

步骤 8

尝试运行查询

{ allArtifacts(group: "com.graphql-java", name: "graphql-java") { group name version } }

实际结果:

1) Chrome 的 控制台 选项卡中的错误:Fetch API cannot load http://localhost:8080/graphql. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8888' is therefore not allowed access. The response had HTTP status code 403. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled..

2) Chrome 的 网络 选项卡中的错误:

更新 2 (14.01.2017 13:51): 目前,CORS 在 Java 应用程序中的配置方式如下。

主要class:

@SpringBootApplication
public class Main {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(Main.class, args);
    }

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry
                        .addMapping("/**")
                        .allowedMethods("OPTIONS")
                        .allowedOrigins("*")
                        .allowedHeaders(
                                "Access-Control-Request-Headers",
                                "Access-Control-Request-Method",
                                "Host",
                                "Connection",
                                "Origin",
                                "User-Agent",
                                "Accept",
                                "Referer",
                                "Accept-Encoding",
                                "Accept-Language",
                                "Access-Control-Allow-Origin"
                        )
                        .allowCredentials(true)
                        ;
            }
        };
    }
}

WebSecurityConfigurerAdapter 子class:

@Configuration
@EnableWebSecurity
public class SpringWebSecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        System.out.println("SpringWebSecurityConfiguration");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("OPTIONS");
        source.registerCorsConfiguration("/**", config);
        http
                .addFilterBefore(new CorsFilter(source), ChannelProcessingFilter.class)
                .httpBasic()
                .disable()
                .authorizeRequests()
                    .anyRequest()
                    .permitAll()
                .and()
                .csrf()
                    .disable();
    }
    @Override
    public void configure(WebSecurity web) throws Exception {
    }
}

控制器:

@Controller
@EnableAutoConfiguration
public class MavenController {
    private final MavenSchema schema = new MavenSchema();
    private final GraphQL graphql = new GraphQL(schema.getSchema());
    private static final Logger log = LoggerFactory.getLogger(MavenController.class);

    @CrossOrigin(
            origins = {"http://localhost:8888", "*"},
            methods = {RequestMethod.OPTIONS},
            allowedHeaders = {"Access-Control-Request-Headers",
            "Access-Control-Request-Method",
            "Host",
            "Connection",
            "Origin",
            "User-Agent",
            "Accept",
            "Referer",
            "Accept-Encoding",
            "Accept-Language",
             "Access-Control-Allow-Origin"},
            exposedHeaders = "Access-Control-Allow-Origin"
             )
    @RequestMapping(value = "/graphql", method = RequestMethod.OPTIONS, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Object executeOperation(@RequestBody Map body) {
        [...]
    }
}

MavenController.executeOperation 是我在 GraphiQL 中发出查询请求时应该调用的方法。

更新 3 (15.01.2017 22:05): 尝试使用 CORSFilter,新的源代码是 here。没有结果,我仍然收到 "Invalid CORS response" 错误。

您必须配置 Spring 调度程序 servlet (http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/DispatcherServlet.html) 来处理选项。

通过 XML 你应该这样做:

  <servlet>
    <servlet-name>yourSpringSvltname</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>dispatchOptionsRequest</param-name>
      <param-value>true</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

通过Java 配置:

 public class MyWebAppInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext container) {
      XmlWebApplicationContext appContext = new XmlWebApplicationContext();
      appContext.setConfigLocation("/WEB-INF/spring/dispatcher-config.xml");

      ServletRegistration.Dynamic dispatcher =
        container.addServlet("dispatcher", new DispatcherServlet(appContext));
dispatchersetDispatchOptionsRequest(true);
      dispatcher.setLoadOnStartup(1);
      dispatcher.addMapping("/");
    }

 }

前段时间我遇到了同样的问题,我通过创建自己的 cors fiter bean 解决了它。

示例:

public class CORSFilter implements Filter {

@Override
public void init(FilterConfig filterConfig) throws ServletException {

}

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
    response.setHeader("Access-Control-Allow-Credentials", "true");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, PUT, OPTIONS");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "accept, access-control-allow-origin, authorization, content-type");

    if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
        response.setStatus(HttpServletResponse.SC_OK);
    } else {
        chain.doFilter(req, res);
    }
}

@Override
public void destroy() {

}

}

并且我在我的配置中定义了它class:

@Bean(name = "corsFilter")
@Order(Ordered.HIGHEST_PRECEDENCE)
public CORSFilter corsFilter() {
    return new CORSFilter();
}

最后在我的 servlet 启动配置中定义了它:

servletContext.addFilter("corsFilter", new DelegatingFilterProxy("corsFilter")).addMappingForUrlPatterns(null, false, "/*");

P.S。希望对您有所帮助。

问题在于您的应用程序中 .allowedMethods("OPTIONS") 配置的使用。

Pre-flight 设计请求使用 OPTIONS 请求方法发送。

Access-Control-Request-Method 由浏览器自动添加,allowedMethods 属性 实际控制实际请求允许的请求方法。

来自docs,

The Access-Control-Request-Method header notifies the server as part of a preflight request that when the actual request is sent, it will be sent with a POST request method.

所以它是 POST 方法并且请求失败,因为您只在验证完成后允许 OPTIONS

因此将 allowedMethods 更改为 * 将匹配浏览器为实际请求设置的 POST 请求方法。

完成上述更改后,您将获得 405,因为您的控制器仅允许 OPTIONS 用于您的 POST 请求。

因此,您需要更新控制器请求映射以允许 POST 实际请求在 pre-flight 请求之后成功。

响应示例:

{
    "timestamp": 1484606833696,
    "status": 500,
    "error": "Internal Server Error",
    "exception": "graphql.AssertException",
    "message": "arguments can't be null",
    "path": "/graphql"
}

我不确定您是否在太多地方设置了 CORS 配置。我只需更改 spring 安全配置中的 .allowedMethods 即可使其按照我描述的方式工作。所以你可能想调查一下。