theArtifacts
theArtifacts

Reputation: 29

Cors Error with AWS Lambda and .Net Core WebAPI

I've created a .Net Core, AWS Lambda WebAPI. Testing locally, I ran into a CORS issue and added a CORS policy to allow origins from my domain. This worked. The app functioned properly.

I need help resolving the cors issue that came after deployment. After deployment to AWS, I'm getting the well known error:


> Access to XMLHttpRequest at 'https://myLambdaEndpoint' from origin
> 'http://myWebsite' has been blocked by CORS policy: Response to
> preflight request doesn't pass access control check: No
> 'Access-Control-Allow-Origin' header is present on the requested
> resource.

Here's what I've done:

My request using Axios in React:

axios.post(`myEndpoint`, { FirstName, LastName, Email })
            .then(res => {
                if(res.errors && res.errors.length > 0) console.log(res.errors);
                else 
                {
                    this.setState({loading: false, registered: true});
                }
            })
            .catch(err => {alert(err); console.log(err)});
    } 

//Also tried

axios.post(`myEndpoint`, {headers: {'Access-Control-Allow-Origin': '*'}, FirstName, LastName, Email })
            .then(res => {
                if(res.errors && res.errors.length > 0) console.log(res.errors);
                else 
                {
                    this.setState({loading: false, registered: true});
                }
            })
            .catch(err => {alert(err); console.log(err)});
    }

in Startup.cs --> Configure Services

services.addCors()

// Also tried

services.AddCors(options =>
            {
                options.AddPolicy("AllowOrigin",
                builder =>
                {
                    builder.WithOrigins("http://myWebsite")
                        .AllowAnyHeader()
                        .WithMethods("POST");
                });
            });

in the controller.cs

        [EnableCors(origins: "http://myWebsite", headers: "*", methods: "post")]

my s3 bucket cors policy for the API as well as for the website

<CORSRule>
    <AllowedOrigin>myWebsite</AllowedOrigin>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>

//Also tried

<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>

I've tried adding triggers to the lambda function in aws as well.

Status code from the preflight is 500. Also says " Referer Policy: no-referer-when-downgrade" I'm wondering if that's the issue?

The response headers are:

> Access-Control-Request-Headers: content-type 
> Access-Control-Request-Method: POST  
> Origin: http://myWebsite.com 
> Referer: http://myWebsite.com/

Anyone know how to fix this? I've spent hours trying things and completing searches.

Upvotes: 2

Views: 2371

Answers (3)

snappymcsnap
snappymcsnap

Reputation: 2103

Hopefully this will also help others who got stuck with this, @theArtifacts has the right idea but you don't actually specifically need to have configured an API Gateway in AWS. If you've created your Web API and published it to Lambda via CLI you can then go into the AWS Console, chose the Lambda Function then choose: Configuration - > Function URL -> EDIT and then expand the 'Additional Settings' section where you will find the CORS policy stuff. Unlike a normally deployed Web API in .NET Core, the following does not work if you're trying to get a quick test working from local machine:

 builder.Services.AddCors(option => {
     option.AddPolicy("AllCors", builder => {
         builder.AllowAnyOrigin();
         builder.AllowAnyHeader();
         builder.AllowAnyMethod();
     });
 });

Upvotes: 0

amatisea
amatisea

Reputation: 33

Just wanted to add after a whole day and a bit of struggling with this issue (.NET Core 5 lambda function). Don't add "/" at the end of the origin domain. i.e. DON'T DO THIS:

services.AddCors(options =>
        {
            options.AddPolicy("AllowOrigin",
            builder =>
            {
                builder.WithOrigins("http://myWebsite/")
                    .AllowAnyHeader()
                    .WithMethods("POST");
            });
        });

Should be this:

services.AddCors(options =>
        {
            options.AddPolicy("AllowOrigin",
            builder =>
            {
                builder.WithOrigins("http://myWebsite")
                    .AllowAnyHeader()
                    .WithMethods("POST");
            });
        });

I know they haven't done that in this question but I had so hope this might save some time for others in the future if they have made the same silly mistake.

Upvotes: 3

theArtifacts
theArtifacts

Reputation: 29

I resolved the issue, no thanks to Google or the AWS documentation.

When I created the.net core lambda deployment I also needed to add an API gateway, and then configure it properly.

In the configuration, I needed to set up each http method I was using as a resource, point it to the lambda function, and set all of its http status responses. Without doing so, the api gateway wouldn't resolve cors.

Hope this helps others!

Upvotes: 0

Related Questions