我正在开发一个Java脚本客户端应用程序,在服务器端我需要处理CORS,以及我用JERSEY用JAX-RS编写的所有服务。我的代码:
@CrossOriginResourceSharing(allowAllOrigins = true) @GET @Path("/readOthersCalendar") @Produces("application/json") public Response readOthersCalendar(String dataJson) throws Exception { //my code. Edited by gimbal2 to fix formatting return Response.status(status).entity(jsonResponse).header("Access-Control-Allow-Origin", "*").build(); }
到目前为止,我收到错误消息请求的资源上没有“ Access-Control-Allow-Origin”标头。因此,不允许访问源’ http:// localhost:8080 ‘。”
“ Access-Control-Allow-Origin”
请协助我。
注意:请务必阅读底部的UPDATE
@CrossOriginResourceSharing 是CXF批注,因此不适用于Jersey。
@CrossOriginResourceSharing
对于Jersey,要处理CORS,我通常只需使用即可ContainerResponseFilter。所述ContainerResponseFilter用于泽西1和2是有点不同。由于您没有提到您使用的是哪个版本,因此我将同时发布两者。
ContainerResponseFilter
Jersey2
import java.io.IOException; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; @Provider public class CORSFilter implements ContainerResponseFilter { @Override public void filter(ContainerRequestContext request, ContainerResponseContext response) throws IOException { response.getHeaders().add("Access-Control-Allow-Origin", "*"); response.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization"); response.getHeaders().add("Access-Control-Allow-Credentials", "true"); response.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD"); } }
如果使用包扫描来发现提供者和资源,则@Provider注释应为您进行配置。如果不是,那么您将需要在ResourceConfig或Application子类中显式注册它。
@Provider
ResourceConfig
Application
使用以下代码显式注册过滤器的示例代码ResourceConfig:
final ResourceConfig resourceConfig = new ResourceConfig(); resourceConfig.register(new CORSFilter()); final final URI uri = ...; final HttpServer httpServer = GrizzlyHttpServerFactory.createHttpServer(uri, resourceConfig);
对于Jersey 2.x,如果在注册此过滤器时遇到问题,这里有一些资源可能会有所帮助
Jersey1
import com.sun.jersey.spi.container.ContainerRequest; import com.sun.jersey.spi.container.ContainerResponse; import com.sun.jersey.spi.container.ContainerResponseFilter; public class CORSFilter implements ContainerResponseFilter { @Override public ContainerResponse filter(ContainerRequest request, ContainerResponse response) { response.getHttpHeaders().add("Access-Control-Allow-Origin", "*"); response.getHttpHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization"); response.getHttpHeaders().add("Access-Control-Allow-Credentials", "true"); response.getHttpHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD"); return response; } }
web.xml配置,可以使用
<init-param> <param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name> <param-value>com.yourpackage.CORSFilter</param-value> </init-param>
或者ResourceConfig你可以做
resourceConfig.getContainerResponseFilters().add(new CORSFilter());
或使用@Provider注释打包扫描。
编辑 请注意,上面的示例可以改进。您将需要更多地了解CORS的工作原理。请看这里。首先,您将获得所有响应的标题。这可能不是理想的。您可能只需要处理印前检查(或选项)。如果您想查看实现更好的CORS过滤器,可以查看RESTeasy的源代码。CorsFilter
更新 因此,我决定添加一个更正确的实现。上面的实现是惰性的,并将所有CORS标头添加到所有请求中。另一个错误是,由于它只是一个响应筛选器,因此请求仍在处理中。这意味着,当预检请求进入时(这是一个OPTIONS请求),将没有实现OPTIONS方法,因此我们将得到405响应,这是不正确的。
这是它应该如何工作的。因此,有两种类型的CORS请求:简单请求和预检请求。对于简单的请求,浏览器将发送实际请求并添加Origin请求标头。浏览器期望响应具有Access-Control-Allow-Origin标头,说Origin允许标头的来源。为了将其视为“简单请求”,它必须满足以下条件:
Accept
Accept-Language
Content-Language
Content-Type
DPR
Save-Data
Viewport-Width
Width
application/x-www-form-urlencoded
multipart/form-data
text/plain
如果该请求不满足所有这三个条件,则发出预检请求。这是在发出实际请求之前向服务器发出的OPTIONS请求。它将包含不同的Access-Control-XX-XX标头,并且服务器应使用自己的CORS响应标头来响应那些标头。以下是匹配的标头:
Access-Control-XX-XX
Preflight Request and Response Headers +-----------------------------------+--------------------------------------+ | REQUEST HEADER | RESPONSE HEADER | +===================================+======================================+ | Origin | Access-Control-Allow-Origin | +-----------------------------------+--------------------------------------+ | Access-Control-Request-Headers | Access-Control-Allow-Headers | +-----------------------------------+--------------------------------------+ | Access-Control-Request-Method | Access-Control-Allow-Methods | +-----------------------------------+--------------------------------------+ | XHR.withCredentials | Access-Control-Allow-Credentials | +-----------------------------------+--------------------------------------+
使用Origin请求标头,该值将是源服务器域,并且响应Access-Control-Allow-Origin应为该相同地址或*指定允许所有源。
Origin
Access-Control-Allow-Origin
如果客户端尝试手动设置不在上述列表中的任何标头,则浏览器将设置Access-Control-Request-Headers标头,该值是客户端尝试设置的所有标头的列表。服务器应使用Access-Control-Allow-Headers响应标头进行响应,该值是其允许的标头列表。
Access-Control-Request-Headers
Access-Control-Allow-Headers
浏览器还将设置Access-Control-Request-Method请求标头,其值为请求的HTTP方法。服务器应使用Access-Control-Allow-Methods响应头进行响应,该值是其允许的方法的列表。
Access-Control-Request-Method
Access-Control-Allow-Methods
如果客户端使用XHR.withCredentials,则服务器应Access-Control-Allow-Credentials使用值为的响应标头进行响应true。在这里阅读更多。
XHR.withCredentials
Access-Control-Allow-Credentials
综上所述,这是一个更好的实现。尽管这比上面的实现要好,但它仍然不如我所链接的RESTEasy,因为此实现仍然允许所有来源。但是,与上述仅向所有请求添加CORS响应标头的过滤器相比,此过滤器在遵守CORS规范方面做得更好。请注意,您可能还需要修改,Access-Control-Allow-Headers以匹配您的应用程序允许的标头;在此示例中,您可能想要o从列表中添加或删除一些标头。
RESTEasy
@Provider @PreMatching public class CorsFilter implements ContainerRequestFilter, ContainerResponseFilter { /** * Method for ContainerRequestFilter. */ @Override public void filter(ContainerRequestContext request) throws IOException { // If it's a preflight request, we abort the request with // a 200 status, and the CORS headers are added in the // response filter method below. if (isPreflightRequest(request)) { request.abortWith(Response.ok().build()); return; } } /** * A preflight request is an OPTIONS request * with an Origin header. */ private static boolean isPreflightRequest(ContainerRequestContext request) { return request.getHeaderString("Origin") != null && request.getMethod().equalsIgnoreCase("OPTIONS"); } /** * Method for ContainerResponseFilter. */ @Override public void filter(ContainerRequestContext request, ContainerResponseContext response) throws IOException { // if there is no Origin header, then it is not a // cross origin request. We don't do anything. if (request.getHeaderString("Origin") == null) { return; } // If it is a preflight request, then we add all // the CORS headers here. if (isPreflightRequest(request)) { response.getHeaders().add("Access-Control-Allow-Credentials", "true"); response.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD"); response.getHeaders().add("Access-Control-Allow-Headers", // Whatever other non-standard/safe headers (see list above) // you want the client to be able to send to the server, // put it in this list. And remove the ones you don't want. "X-Requested-With, Authorization, " + "Accept-Version, Content-MD5, CSRF-Token, Content-Type"); } // Cross origin requests can be either simple requests // or preflight request. We need to add this header // to both type of requests. Only preflight requests // need the previously added headers. response.getHeaders().add("Access-Control-Allow-Origin", "*"); } }
要了解有关CORS的更多信息,建议阅读有关跨域资源共享(CORS)的MDN文档