繁体   English   中英

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

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

我正在尝试使GraphQL Java服务器与GraphiQL服务器一起使用。

使用本地运行的GraphiQL,我使用以下参数提交查询:

GraphiQL查询及其结果

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

@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 不是,我在控制台输出中看不到log语句。

我在做什么? 我怎样才能确保MavenController.executeOperation被调用,当查询在GraphiQL提交?

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

我已阅读此书 ,需要执行以下步骤:

  1. 设置一个GraphQL服务器。 可以在这里找到一个示例https://github.com/graphql-java/todomvc-relay-java 该示例使用Spring Boot,但是您可以使用任何喜欢的HTTP服务器来实现这一目标。
  2. 设置GraphiQL服务器。 这有点超出该项目的范围,但是基本上您需要在上面的步骤1中使GraphiQL与服务器通信。 它将使用自省来加载架构。

我签出了项目todomvc-relay-java ,根据需要对其进行了修改,并将其放入目录E:\\graphiql-java\\graphql-server 您可以在此处下载具有该目录的存档。

步骤1:安装Node.JS

第2步

转到E:\\graphiql-java\\graphql-server\\app然后在此处运行npm install

第三步

从同一目录运行npm start

第四步

转到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步

使用禁用的XSS检查启动Chrome,例如"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. 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):当前,通过以下方式在Java应用程序中配置了CORS。

主班:

@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子类:

@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 ,新的源代码在这里 没有结果,我仍然收到“无效的CORS响应”错误。

您必须配置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 Config:

 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() {

}

}

我在配置类中定义了它:

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

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

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

PS希望这会对您有所帮助。

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

设计前使用OPTIONS请求方法发送的飞行前请求。

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

文档中

Access-Control-Request-Method标头将作为预检请求的一部分通知服务器,当发送实际请求时,将使用POST请求方法发送该请求。

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

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

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

因此,您将需要更新控制器请求映射,以允许POST实际请求在飞行前请求之后成功。

样本响应:

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

我不确定您在太多地方设置了CORS配置。 我只需要在spring安全配置中更改.allowedMethods即可使其按我描述的方式工作。 因此,您可能需要调查一下。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM