DevilCode
DevilCode

Reputation: 1100

CORS AWS using Lambda (JAVA)

I am using AWS API Gateway with a Java Lambda Backend. Everything is peachy until a friend using Angular 4 is trying to make requests. He keeps getting:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at URL (Reason: CORS header 'Access-Control-Allow-Origin' missing).

I have enabled CORS via the gateway:

AWS image

Despite this the error remains. What should I modify ?

Thanks.

Ian's Comments: I use Output/Input Streams so my output, as per your comment I am trying as below but still no success. Any ideas ?

private void sendResponse(JSONObject body, int statusCode, OutputStream outputStream)
{   
    OutputStreamWriter writer;                                                             
    JSONObject responseJson = new JSONObject(); 
    JSONObject responseHeadersJson = new JSONObject();
    responseHeadersJson.put("Access-Control-Allow-Origin","*");
    responseHeadersJson.put("Access-Control-Allow-Headers","Content-Type");

    responseJson.put("headers",responseHeadersJson);
    responseJson.put("statusCode", statusCode);
    responseJson.put("body", body.toJSONString());          
    try {
        writer = new OutputStreamWriter(outputStream, "UTF-8");
        writer.write(responseJson.toJSONString());  
        writer.close(); 
    } catch (IOException e) {
        System.out.println("Outputstream Error "+e);
    }}

Upvotes: 4

Views: 2568

Answers (1)

ian1095
ian1095

Reputation: 579

I can see that you are using Proxy Resource.

That means you are controlling the response thats going back as well from your Lambda. CORS needs to be configured on the response as well by adding the origin header.

When you build the response you need to add the cors headers by passing the domain or *.

I have built a ResponseBuilder that you can use as an example:

https://github.com/ahpoi/commons-utils-sdk/blob/master/src/main/java/com/ahpoi/commons/utils/aws/lambda/model/proxy/response/ResponseBuilder.java

public ResponseBuilder originHeader(String domain) {
    headers.put(ACCESS_CONTROL_ALLOW_ORIGIN, domain);
    return this;
}

private void initDefaultHeaders() {
    headers.put(ACCESS_CONTROL_ALLOW_HEADERS, "Content-Type");
}

public Response build() {
    this.initDefaultHeaders();
    return new Response(statusCode, headers, body);
}

If you didn't use Proxy Resource, your configuration would have been enough.

Upvotes: 3

Related Questions