Dropwizard 0.8 - 启用CORS

时间:2015-04-11 00:01:05

标签: java cors dropwizard

有谁知道如何为dropwizard 0.8启用CORS?我只能找到有关版本0.7 here的信息。

显然这没有用

FilterRegistration.Dynamic filter = environment.servlets().addFilter(
                "CORS", CrossOriginFilter.class);
        // Add URL mapping
        filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class),
                true, "/*");
        filter.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM,
                "GET,PUT,POST,DELETE,OPTIONS");
        filter.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*");
        filter.setInitParameter(
                CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*");
        filter.setInitParameter("allowedHeaders",
                "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin");
        filter.setInitParameter("allowCredentials", "true");

2 个答案:

答案 0 :(得分:1)

以上应该有效。我已经编写了一个单元测试的工作要点:https://gist.github.com/yunspace/07d80a9ac32901f1e149,它针对0.8.1和0.9.0-SNAPSHOT进行了测试。将其作为参考运行。

如果您遇到问题,请尝试将日志级别设置为DEBUG,如@elec建议:

loggers:
   org.eclipse.jetty.servlets: DEBUG

当CrossOriginFilter初始化时,它应打印出以下日志条目:

DEBUG [2015-05-07 11:55:39,247] org.eclipse.jetty.servlets.CrossOriginFilter: Cross-origin filter configuration: allowedOrigins = *, allowedMethods = GET,PUT,POST,DELETE,OPTIONS, allowedHeaders = Origin, Content-Type, Accept, Authorization, preflightMaxAge = 1800, allowCredentials = true,exposedHeaders = ,chainPreflight = true

答案 1 :(得分:0)

我已经苦苦挣扎了近一个星期,我会在这里发布我的代码,对于那些感兴趣的人,基本上步骤是一样的:  1.将其包含在您的应用程序类中 final FilterRegistration.Dynamic filter = environment.servlets()。addFilter(“CORSFilter”,CrossOriginFilter.class);

    System.setProperty("sun.net.http.allowRestrictedHeaders", "true");

    //filter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, environment.getApplicationContext().getContextPath() + "*");
    // Configure CORS parameters
    filter.setInitParameter("allowedOrigins", "*");
    filter.setInitParameter("allowedHeaders", "X-Requested-With,Content-Type,Accept,Origin");
    filter.setInitParameter("allowedMethods", "OPTIONS,GET,PUT,POST,DELETE,HEAD");
    // Add URL mapping
    filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
  1. 在当前资源上提供响应时,请明确包含您的选项。

    return Response.status(status)
            .entity(new MessageResponse(this.counter.incrementAndGet(), message, response))
            .header("Access-Control-Allow-Origin", origin.isPresent() ? origin.get():"*")
            .header("Access-Control-Allow-Methods", methods)
            .header("Access-Control-Allow-Headers", "Content-Type, header-task")
            .type(MediaType.APPLICATION_JSON)
            .encoding("UTF-8")
            .allow(allow)
            .build();