1

I want to restrict my Lambda function (created with the Serverless Framework tool) to accept requests only from abc.com and def.com. It should reject all other requests. How can I do this? I tried setting access control origins like this:

cors: true
response:
  headers:
    Access-Control-Allow-Origin: "'beta.leafycode.com leafycode.com'"

and like this in the handler:

headers: {
  "Access-Control-Allow-Origin" : "beta.leafycode.com leafycode.com"
},

but nothing worked. Any idea why?

Zanon
  • 22,850
  • 18
  • 101
  • 110
THpubs
  • 6,509
  • 12
  • 52
  • 120

1 Answers1

2

The issue with your code is that Access-Control-Allow-Origin doesn't accept multiple domains.

From this answer:

Sounds like the recommended way to do it is to have your server read the Origin header from the client, compare that to the list of domains you'd like to allow, and if it matches, echo the value of the Origin header back to the client as the Access-Control-Allow-Origin header in the response.

So, when writing support to the OPTIONS verb, which is the verb where the browser will preflight a request to see if CORS is supported, you need to write your Lambda code to inspect the event object to see the domain of the client and dynamically set the corresponding Access-Control-Allow-Origin with the domain.

In your question, you have used a CORS configuration for two different types: Lambda and Lamba-Proxy. I recommend that you use the second option, so you will be able to set the domain dynamically.

headers: {
  "Access-Control-Allow-Origin" : myDomainValue
},

See more about CORS configuration in the Serverless Framework here.

Zanon
  • 22,850
  • 18
  • 101
  • 110
  • Hi, I just tried with one domain and sill it's not restricting the requests. – THpubs Jun 26 '17 at 10:35
  • 1
    @THpubs, if you are setting the headers in the handler, as I have suggested, make sure that you **don't** have the option `integration: lambda` in your `serverless.yml` file. If it still doesn't work, I suggest that you create a new hello-world project to test just this feature, so we may eliminate another misconfiguration. – Zanon Jun 26 '17 at 11:08
  • 1
    Great thanks it worked! Removing the integration fixed the issue. – THpubs Jun 26 '17 at 13:50