Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access-Control-Allow-Origin Limit

I have set up our public facing website with the header Access-Control-Allow-Origin: * so that we can use JSON and AJAX. However, what I really want to do is limit it to only certain servers. The requests should only ever come from a few servers that we control. I am having trouble finding something works without adding in code (example psuedo-code):

for each domain in myDomains
    addheader Access-Control-Allow-Origin: domain
next

Is it possible to just add multiple "Access-Control-Allow-Origin" in IIS under the HTTP Headers tab? I know that it is possible to actually add it to IIS, but does it work?

Example:

Access-Control-Allow-Origin: http://domain1
Access-Control-Allow-Origin: http://domain2
Access-Control-Allow-Origin: http://127.0.0.1 (use using home as IP example)

Using Access-Control-Allow-Origin: * is just to insecure.

like image 321
Stanley Glass Jr Avatar asked Jun 11 '13 14:06

Stanley Glass Jr


People also ask

How do I fix Access-Control allow origin?

Since the header is currently set to allow access only from https://yoursite.com , the browser will block access to the resource and you will see an error in your console. Now, to fix this, change the headers to this: res. setHeader("Access-Control-Allow-Origin", "*");

Is it safe to use Access-Control allow origin?

Access-Control-Allow-Origin: * is totally safe to add to any resource, unless that resource contains private data protected by something other than standard credentials. Standard credentials are cookies, HTTP basic auth, and TLS client certificates.

Can you have multiple Access-Control allow Origin headers?

More than one Access-Control-Allow-Origin header was sent by the server. This isn't allowed.

What happens if Access-Control allow origin is not set?

This is a security feature for avoiding everyone freely accessing any resources of that domain (which can be accessed for example to have an exact same copy of your website on a pirate domain). The header of the response, even if it's 200OK do not allow other origins (domains, port) to access the resources.


1 Answers

No, multiple Access-Control-Allow-Origin headers are not allowed. You can only have one Access-Control-Allow-Origin response header, and that header can only have one origin value or * (e.g. you can't have multiple space-separated origins).

Your best option is to read the incoming Origin header, check its value against a whitelist, and only emit the Access-Control-Allow-Origin header if the Origin is allowed. Here's an example in pseudo-code:

origin = request.getHeader('Origin');
for each domain in myDomains
  if (domain == origin)
    // Add header if the origin is whitelisted
    addheader Access-Control-Allow-Origin: domain
    return
// Otherwise exit the for loop without adding any headers.
like image 158
monsur Avatar answered Nov 15 '22 08:11

monsur