使用CORS头过滤器与dropwizard 0.7.0

时间:2014-07-03 07:16:19

标签: java filter jersey cors dropwizard

我正在尝试使用dropwizard 0.7.0(Jersey)REST服务来发送HTML CORS标头,例如" Access-Control-Allow-Origin"。我找到了各种教程,并了解了在0.7.0和之前版本中如何做到这一点的差异。最有希望的方式似乎是described in the dropwizard group,但是当我使用给定的代码时,不会发送任何标头。过滤器似乎不起作用。当我使用自定义过滤器时,它正在初始化但不会被使用。到目前为止,日志中没有任何异常。

这是我的(最新)运行方法:

        @Override
public void run(BackendConfiguration configuration, Environment environment) throws Exception {

    // XXX why doesn't this work?
    FilterRegistration.Dynamic filter = environment.servlets().addFilter("CORS", CrossOriginFilter.class);
    filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
    filter.setInitParameter("allowedOrigins", "*"); // allowed origins comma separated
    filter.setInitParameter("allowedHeaders", "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin");
    filter.setInitParameter("allowedMethods", "GET,PUT,POST,DELETE,OPTIONS,HEAD");
    filter.setInitParameter("preflightMaxAge", "5184000"); // 2 months
    filter.setInitParameter("allowCredentials", "true");


    final DBIFactory factory = new DBIFactory();
    final DBI jdbi = factory.build(environment, configuration.getDataSourceFactory(), "h2");

    environment.jersey().register(new UserResource(jdbi));
}

我做错了吗?

1 个答案:

答案 0 :(得分:3)

来自CrossOriginFilter:

    String origin = request.getHeader(ORIGIN_HEADER);
    // Is it a cross origin request ?
    if (origin != null && isEnabled(request))

您必须在请求中发送Origin标头以使过滤器正常工作。