在 dropwizard 中启用 cors 不起作用

2022-09-01 21:32:29

我正在开发一个dropwizard应用程序和js ui来与api进行交互。我需要加载json数据来更新视图,但在此之前我必须在dropwizard中启用cors。我做了一些工作人员,但它似乎不起作用,因为dropwizard返回allways 204没有内容。

@Override
public void run(final BGConfiguration configuration, final Environment environment) throws Exception {
  final Map<String, String> params = new HashMap<>();
  params.put("Access-Control-Allow-Origin", "/*");
  params.put("Access-Control-Allow-Credentials", "true");
  params.put("Access-Control-Expose-Headers", "true");
  params.put("Access-Control-Allow-Headers", "Content-Type, X-Requested-With");
  params.put("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
  environment.servlets().addFilter("cors", CrossOriginFilter.class).setInitParameters(params);
}

答案 1

此处的错误是尚未通过该方法使用 URL 路径配置筛选器。addMappingForUrlPatterns

这适用于我使用dropwizard 0.7.1:

import org.eclipse.jetty.servlets.CrossOriginFilter;
import javax.servlet.DispatcherType;
import java.util.EnumSet;

public void run(Configuration conf, Environment environment)  {
    // Enable CORS headers
    final FilterRegistration.Dynamic cors =
        environment.servlets().addFilter("CORS", CrossOriginFilter.class);

    // Configure CORS parameters
    cors.setInitParameter("allowedOrigins", "*");
    cors.setInitParameter("allowedHeaders", "X-Requested-With,Content-Type,Accept,Origin");
    cors.setInitParameter("allowedMethods", "OPTIONS,GET,PUT,POST,DELETE,HEAD");

    // Add URL mapping
    cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
}

我假设您正在浏览器中实时测试此功能,但是您可以使用CLI使用curl命令进行验证,如下所示:

$ curl -H "Origin: http://example.com" \
       -H "Access-Control-Request-Method: POST" \
       -H "Access-Control-Request-Headers: X-Requested-With" \
       -X OPTIONS --verbose \
       http://localhost:8080

您应该在响应中看到一堆 HTTP 标头。Access-Control-*


答案 2

补充迈克·克拉克的回答:

将 设置为 false 将允许此筛选器处理预检请求,而无需身份验证筛选器拦截响应并将其转换为未经授权/禁止的响应。CHAIN_PREFLIGHT_PARAM200

import org.eclipse.jetty.servlets.CrossOriginFilter;
import javax.servlet.DispatcherType;
import java.util.EnumSet;

public void run(Configuration conf, Environment environment)  {
    // Enable CORS headers
    final FilterRegistration.Dynamic cors =
        environment.servlets().addFilter("CORS", CrossOriginFilter.class);

    // Configure CORS parameters
    cors.setInitParameter("allowedOrigins", "*");
    cors.setInitParameter("allowedHeaders", "X-Requested-With,Content-Type,Accept,Origin");
    cors.setInitParameter("allowedMethods", "OPTIONS,GET,PUT,POST,DELETE,HEAD");

    // Add URL mapping
    cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");

    // DO NOT pass a preflight request to down-stream auth filters
    // unauthenticated preflight requests should be permitted by spec
    cors.setInitParameter(CrossOriginFilter.CHAIN_PREFLIGHT_PARAM, Boolean.FALSE.toString());
}

我很惊讶我没有在互联网上找到任何包含此配置的示例。花了几天时间试图弄清楚这一点。


推荐