7

I need to implement CORS support in Jersey based REST server. I've gone through some of the available material and informative tutorials . I found two approaches people are using:

Approach-1 :

Simple and direct approach where implement one HTTP filter which adds CORS header to response (Jersey specific)

public class ResponseCorsFilter implements ContainerResponseFilter {

public ContainerResponse filter(ContainerRequest req, ContainerResponse contResp) {

        ResponseBuilder resp = Response.fromResponse(contResp.getResponse());
        resp.header("Access-Control-Allow-Origin", "*")
                .header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");

        String reqHead = req.getHeaderValue("Access-Control-Request-Headers");

        if(null != reqHead && !reqHead.equals(null)){
            resp.header("Access-Control-Allow-Headers", reqHead);
        }

        contResp.setResponse(resp.build());
            return contResp;
    }
}

Approach-2 :

Fully implement CORS as per its specification i.e. preflight request handling and all header support. Inspected source code of one such open-source java implementation cors-filter

My question is which approach should be taken when? What could be the downside of approach-1 vs approach-2?

My use case is all origins/methods can be allowed and Authorization HTTP header would be part of all REST requests. I am inclined towards approach-1 as it seems most of the default CORS settings would suffice my use case but not sure if not having full CORS specs implemented at server side would create any issues whatsoever.

4

2 回答 2

2

出于您的目的,方法#1 听起来就足够了。方法 #2 更适用于根据请求类型有不同响应的情况,或者您想要验证请求信息。如果您的响应在所有请求类型中都相同,则 #1 应该没问题。请注意,由于您的实现基本上允许所有请求成功,因此您应该进行自己的检查以确保请求有效。由于您允许 Authorization 标头,我假设您知道这一点,并且正在验证授权令牌?

于 2013-04-18T14:58:51.610 回答
0

对于那些在 Play Framework 中遇到问题的人,这里有一个解决方案,大多数文本是葡萄牙语,但您可以使用谷歌翻译。

解决方案是一样的。

http://www.igorcosta.com/habilitando-cors-no-play-framework-2-3-x/

于 2014-12-08T18:30:52.943 回答