Search code examples
javacorsgoogle-cloud-endpoints

App Engine Endpoint enable CORS


I have an some methods in the Standard Environment v2 endpoint class. When calling them from the web client first OPTIONS method is called to check if CORS is enabled. Response is:

HTTP/1.1 200 OK
X-Cloud-Trace-Context: 2a246f2e7f7ddbbf2afeaa71629da259;o=1
Date: Wed, 12 Jul 2017 13:47:20 GMT
Expires: Wed, 12 Jul 2017 13:47:20 GMT
Cache-Control: private, max-age=0
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
Content-Length: 0
Server: GSE
Content-Type: text/html; charset=UTF-8
Alt-Svc: quic=":443"; ma=2592000; v="39,38,37,36,35"

What is missing here is the Access-Control-Allow-Origin: * response header. Is there any way to enable it?


Solution

  • The problem described in answer was my fault (what a surprise). For other having a problem with configuring CORS on GAE: If CORS is set up out of the box. But for getting the right response you also have to have the right request:

    Origin: null
    Access-Control-Request-Method: GET
    

    Method must be one of the following: "HEAD", "DELETE", "GET", "PATCH", "POST", "PUT" Origin can be virtually any string - you'll get it back in the response. "null" is a special keyword that is translated to "*". This is the code responsible for header generation (from GAE sources):

      public static void allowOrigin(HttpServletRequest request, HttpServletResponse response) {
        String origin = request.getHeader(Headers.ORIGIN);
        // The Origin spec (http://tools.ietf.org/html/draft-abarth-origin-09) allows for the Origin
        // http header value to be "null". This is for cases where a request doesn't have a valid
        // origin; for example, issuing a CORS request from a local file:// rather than a website. In
        // these cases, we'd like to enable CORS to facilitate testing; the mechanism for doing so is
        // to set the Access-Control-Allow-Origin header to '*'.
        origin = NULL_ORIGIN.equals(origin) ? "*" : origin;
        response.setHeader(Headers.ACCESS_CONTROL_ALLOW_ORIGIN, origin);
      }
    

    My secondary problem was unstable build due to wrong merged Gradle file.