java 在 dropwizard 中启用 cors 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25775364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 08:40:12  来源:igfitidea点击:

Enabling cors in dropwizard not working

javadropwizard

提问by naslami

I'm working on a dropwizard application and js ui to interacte with the api. I need to load json data to update views but I have to enable cors in dropwizard before that. I did some staff but it seems not working because dropwizard returns allways 204 no content.

我正在开发一个 dropwizard 应用程序和 js ui 来与 api 交互。我需要加载 json 数据来更新视图,但在此之前我必须在 dropwizard 中启用 cors。我做了一些工作人员,但它似乎不起作用,因为 dropwizard 总是返回 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);
}

回答by Mike Clarke

The bug here is that the filter hasn't been configured with a URL path via the addMappingForUrlPatternsmethod.

这里的错误是过滤器没有通过addMappingForUrlPatterns方法配置 URL 路径。

This worked for me using dropwizard 0.7.1:

这对我使用 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, "/*");
}

I'm assuming you're testing this live in a browser, but you can verify via CLI with a curl command like this:

我假设您正在浏览器中对此进行实时测试,但您可以通过 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

You should see a bunch of Access-Control-*HTTP headers in the response.

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

回答by Jimi

Adding to Mike Clarke's answer:

添加迈克克拉克的回答:

Setting the CHAIN_PREFLIGHT_PARAMto falsewill let this filter handle preflight requests without your authentication filters intercepting what would be a 200response and turning them into unauthorized / forbidden.

将 设置CHAIN_PREFLIGHT_PARAMfalse将让此过滤器处理预检请求,而无需您的身份验证过滤器拦截200响应并将它们变成未经授权的/禁止的。

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());
}

I was surprised that I didn't find any examples on the interwebs that included this configuration. Spent a few days trying to figure this out.

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

回答by Atul Soman

For me even after configuring the above, it was not working. Ultimately it turned out that i have to also allow cache-control headers.

对我来说,即使在配置了上述内容后,它也不起作用。最终结果是我还必须允许缓存控制标头。

filter.setInitParameter("allowedHeaders",
"Cache-Control,If-Modified-Since,Pragma,Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin");

回答by Mehul Gupta

you can try doing this:

你可以尝试这样做:

final FilterRegistration.Dynamic cors =
        environment.servlets().addFilter("CORS", CrossOriginFilter.class);

// Configure CORS parameters
// Configure CORS parameters
cors.setInitParameter("allowedOrigins", "*");
cors.setInitParameter("allowedHeaders", “<Headers>”);
cors.setInitParameter("allowedMethods", "OPTIONS,GET,PUT,POST,");

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