corydolphin / flask-cors

Cross Origin Resource Sharing ( CORS ) support for Flask
https://flask-cors.corydolphin.com/
MIT License
877 stars 137 forks source link

Can't get @cross_origin to work with create_app #226

Closed fenekku closed 6 years ago

fenekku commented 6 years ago

Hi,

I must be doing something wrong here. I have a very simple app using @cross_origin on a view but CORS headers are not sent back or respected on tests with cURL:

# __init__.py
from flask import Flask
from flask_cors import cross_origin

def create_app(test_config=None):
    app = Flask(__name__, instance_relative_config=True)
        # ensure the instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    @app.route('/lat/<latitude>/long/<longitude>')
    @cross_origin(origins='http://example.com')
    def weather(longitude, latitude):
        return 'content'

I am expecting the call below to fail since only http://example.com is allowed and the Origin header is being spoofed to http://example123.com. This is what I get however:

curl -H "Origin: http://example123.com" --verbose http://127.0.0.1:5000/lat/42.3601/long/-71.0589
*   Trying 127.0.0.1...
* Connected to 127.0.0.1 (127.0.0.1) port 5000 (#0)
> GET /lat/42.3601/long/-71.0589 HTTP/1.1
> Host: 127.0.0.1:5000
> User-Agent: curl/7.47.0
> Accept: */*
> Origin: http://example123.com
>
* HTTP 1.0, assume close after body
< HTTP/1.0 200 OK
< Content-Type: text/html; charset=utf-8
< Content-Length: 7
< Server: Werkzeug/0.14.1 Python/2.7.12
< Date: Sun, 17 Jun 2018 22:24:27 GMT
<
* Closing connection 0
content⏎             

with Python 3.6.5 I get the same result. I am expecting Access-Control-Allow-Origin: http://example.com to be returned from the server but it is not.

What is missing? Is this a bug?

corydolphin commented 6 years ago

Hello,

If that is an exact configuration example, the issue is that the origins specified does not match the Origin header. http://example123.com will not match http://example.com. Update the specified origins to http://example123.com and things should work as you expect.

Cheers, Cory

fenekku commented 6 years ago

Oh! The Access-Control-Allow-Origin: http://example.com (and family) header is only returned for a request with Origin that matches the allowed policy and no such headers are returned at all for other requests without a matching Origin. This is probably done:

Does that sound right? I will test tonight.

Thanks!

corydolphin commented 6 years ago

@fenekku That's on the right track! Let me know how it goes.

fenekku commented 6 years ago

It works as intended! Thank you for validating!