4

I have implemented CORS on my Google App Engine Python app with this code:

    approved_origin = 'https://example.com'
    self.response.headers.add_header('Access-Control-Allow-Origin', approved_origin)

The problem is that I could like to allow more than one approved origin, and would like to allow both http and https.

Does anyone know if this can be done, and if so, what is the syntax? I do not want to allow all origins with '*'.

konqi
  • 5,137
  • 3
  • 34
  • 52
Tim Doyle
  • 43
  • 3

2 Answers2

7

You have to maintain a whitelist of allowed origins and include the CORS header if the current request comes from an approved origin. Something like this should work:

approved_origins = ['https://example.com', 'https://example.info']
if self.request.headers['Origin'] in approved_origins:
  self.response.headers.add_header('Access-Control-Allow-Origin', self.request.headers['Origin'])
abraham
  • 46,583
  • 10
  • 100
  • 152
  • Yep! The "secret" is that HTTP headers may be repeated, and for several of them (inc. A-C-A-O) the repetition is *meaningful*. In theory, per RFC 2616, that *should* be equivalent to a comma-separated list value in a single header... but A-C-A-O implementations are notoriously balky about that! – Alex Martelli Nov 21 '15 at 17:10
0

To complement: https://stackoverflow.com/a/14006226/3203254

The CORS spec is all-or-nothing. It only supports *, null or the exact domain: http://www.w3.org/TR/cors/#access-control-allow-origin-response-header

Your server will need to validate the origin header using the regex, and then you can echo the origin value in the Access-Control-Allow-Origin response header.

Community
  • 1
  • 1