Skip to content

Problem with CORS origin headers when creating it via Terraform

0

Hello guys,

I am trying to create an API GTW with Terraform, and after some struggle the API is returning the proper response. Now, I need to set up CORS with Terraform, but it is not enabling the origin header. I used Amazon Q to create the tf and also change the Lambda function. Below is the error I am receiving and on the bottom it is my cors.tf and API gtw.tf. Could someone take a look at this?

Access to fetch at 'https://bcf6k7cwy7.execute-api.us-east-1.amazonaws.com/dev/read' from origin 'https://www.umamicloudchallenge.org' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

This when a curl the API with Options: allan@ALLAN-Z:~/cloudchallenge/terraform/frontend$ curl -v -X OPTIONS https://bcf6k7cwy7.execute-api.us-east-1.amazonaws.com/dev/read

  • Trying 54.204.230.182:443...
  • Connected to bcf6k7cwy7.execute-api.us-east-1.amazonaws.com (54.204.230.182) port 443 (#0)
  • ALPN, offering h2
  • ALPN, offering http/1.1
  • CAfile: /etc/ssl/certs/ca-certificates.crt
  • CApath: /etc/ssl/certs
  • TLSv1.0 (OUT), TLS header, Certificate Status (22):
  • TLSv1.3 (OUT), TLS handshake, Client hello (1):
  • TLSv1.2 (IN), TLS header, Certificate Status (22):
  • TLSv1.3 (IN), TLS handshake, Server hello (2):
  • TLSv1.2 (IN), TLS header, Finished (20):
  • TLSv1.2 (IN), TLS header, Supplemental data (23):
  • TLSv1.3 (IN), TLS handshake, Encrypted Extensions (8):
  • TLSv1.2 (IN), TLS header, Supplemental data (23):
  • TLSv1.3 (IN), TLS handshake, Certificate (11):
  • TLSv1.2 (IN), TLS header, Supplemental data (23):
  • TLSv1.3 (IN), TLS handshake, CERT verify (15):
  • TLSv1.2 (IN), TLS header, Supplemental data (23):
  • TLSv1.3 (IN), TLS handshake, Finished (20):
  • TLSv1.2 (OUT), TLS header, Finished (20):
  • TLSv1.3 (OUT), TLS change cipher, Change cipher spec (1):
  • TLSv1.2 (OUT), TLS header, Supplemental data (23):
  • TLSv1.3 (OUT), TLS handshake, Finished (20):
  • SSL connection using TLSv1.3 / TLS_AES_128_GCM_SHA256
  • ALPN, server accepted to use h2
  • Server certificate:
  • subject: CN=*.execute-api.us-east-1.amazonaws.com
  • start date: Mar 22 00:00:00 2025 GMT
  • expire date: Apr 19 23:59:59 2026 GMT
  • subjectAltName: host "bcf6k7cwy7.execute-api.us-east-1.amazonaws.com" matched cert's "*.execute-api.us-east-1.amazonaws.com"
  • issuer: C=US; O=Amazon; CN=Amazon RSA 2048 M03
  • SSL certificate verify ok.
  • Using HTTP2, server supports multiplexing
  • Connection state changed (HTTP/2 confirmed)
  • Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0
  • TLSv1.2 (OUT), TLS header, Supplemental data (23):
  • TLSv1.2 (OUT), TLS header, Supplemental data (23):
  • TLSv1.2 (OUT), TLS header, Supplemental data (23):
  • Using Stream ID: 1 (easy handle 0x560b4df429f0)
  • TLSv1.2 (OUT), TLS header, Supplemental data (23):

OPTIONS /dev/read HTTP/2 Host: bcf6k7cwy7.execute-api.us-east-1.amazonaws.com user-agent: curl/7.81.0 accept: /

  • TLSv1.2 (IN), TLS header, Supplemental data (23):
  • TLSv1.3 (IN), TLS handshake, Newsession Ticket (4):
  • TLSv1.2 (IN), TLS header, Supplemental data (23):
  • Connection state changed (MAX_CONCURRENT_STREAMS == 128)!
  • TLSv1.2 (OUT), TLS header, Supplemental data (23):
  • TLSv1.2 (IN), TLS header, Supplemental data (23):
  • TLSv1.2 (IN), TLS header, Supplemental data (23): < HTTP/2 200 < date: Tue, 01 Jul 2025 18:53:49 GMT < content-type: application/json < content-length: 0 < x-amzn-requestid: 7bf83ef3-c0d2-4b99-87bd-972aa641e35c < access-control-allow-origin: https://www.umamicloudchallenge.org < access-control-allow-headers: Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token < x-amz-apigw-id: NCw9nHkWoAMEfqA= < access-control-allow-methods: POST,OPTIONS <
  • Connection #0 to host bcf6k7cwy7.execute-api.us-east-1.amazonaws.com left intact

Here is my cors.tf > https://separately-modern-louse-bucket.s3.us-east-2.amazonaws.com/cors.tf And here is the API gw > https://separately-modern-louse-bucket.s3.us-east-2.amazonaws.com/rest_api_gtw.tf

I appreciate any help!

Allan

2 Answers
0

Hello.

Although you cannot see the Terraform code due to AccessDenied, I think you can troubleshoot general CORS errors when using API Gateway and Lambda by following the steps in the following document.
After enabling CORS in API Gateway, deploy the API.
In addition to configuring API Gateway, make sure that the code is written so that the Lambda response returns "Access-Control-Allow-Origin" or similar.
https://repost.aws/knowledge-center/api-gateway-cors-errors
https://www.cloudtechsimplified.com/cors-error-api-gateway-aws-lambda/

EXPERT
answered 10 months ago
  • Thank you for answering. My Lambda code already includes the headers in the return:

    return { 'statusCode': 200, 'headers': { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': 'https://www.umamicloudchallenge.org', 'Access-Control-Allow-Headers': 'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token', 'Access-Control-Allow-Methods': 'POST,OPTIONS' },

  • The full code:

    import boto3 # type: ignore
    import json
    
    table_name = "count-table"
    dynamo = boto3.resource('dynamodb').Table(table_name)
    
    def read(payload):
    
        return dynamo.get_item(Key=payload['Key'])
    
    operations = {'read': read}
    
    def lambda_handler(event, context):
        try:
            # Check if the request is coming from API Gateway
            if 'body' in event and isinstance(event['body'], str):
                # Parse the body from API Gateway
                body = json.loads(event['body'])
                operation = body['operation']
                payload = body['payload']
            else:
                # Direct Lambda invocation
                operation = event['operation']
                payload = event['payload']
    
            if operation in operations:
                result = operations[operation](payload)
                return {
                    'statusCode': 200,
                    'headers': {
                        'Content-Type': 'application/json',
                        'Access-Control-Allow-Origin': 'https://www.umamicloudchallenge.org',
                        'Access-Control-Allow-Headers': 'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token',
                        'Access-Control-Allow-Methods': 'POST,OPTIONS'
                    },
                    'body': json.dumps(result, default=str)
                }
            else:
                return {
                    'statusCode': 400,
                    'headers': {
                        'Content-Type': 'application/json',
                        'Access-Contro
    
0

If you are using Lambda in Proxy mode on APi Gateway , you will need to include the CORS policy in the response from the Lambda function

EXPERT
answered 10 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.