Python Flask CORS - API always allows any origin - python

I've looked through many SO answers, and can't seem to find this issue. I have a feeling that I'm just missing something obvious.
I have a basic Flask api, and I've implemented both the flask_cors extension and the custom Flask decorator [#crossdomain from Armin Ronacher].1 (http://flask.pocoo.org/snippets/56/) Both show the same issue.
This is my example app:
application = Flask(__name__,
static_url_path='',
static_folder='static')
CORS(application)
application.config['CORS_HEADERS'] = 'Content-Type'
#application.route('/api/v1.0/example')
#cross_origin(origins=['http://example.com'])
# #crossdomain(origin='http://example.com')
def api_example():
print(request.headers)
response = jsonify({'key': 'value'})
print(response.headers)
return response
(EDIT 3 inserted):
When I make a GET request to that endpoint from JS in a browser (from 127.0.0.1), it always returns 200, when I would expect to see:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:5000' is therefore not allowed access. The response had HTTP status code 403.
CURL:
ACCT:ENVIRON user$ curl -i http://127.0.0.1:5000/api/v1.0/example
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 20
Access-Control-Allow-Origin: http://example.com
Server: Werkzeug/0.11.4 Python/2.7.11
Date: [datetime]
{
"key": "value"
}
LOG:
Content-Length:
User-Agent: curl/7.54.0
Host: 127.0.0.1:5000
Accept: */*
Content-Type:
Content-Type: application/json
Content-Length: 20
127.0.0.1 - - [datetime] "GET /api/v1.0/example HTTP/1.1" 200 -
I'm not even seeing all of the proper headers in the response, and it doesn't seem to care what the origin is in the request.
Any ideas what I'm missing? Thanks!
EDIT:
As a side note, looking at the documentation example here (https://flask-cors.readthedocs.io/en/v1.7.4/#a-more-complicated-example), it shows:
#app.route("/")
def helloWorld():
'''
Since the path '/' does not match the regular expression r'/api/*',
this route does not have CORS headers set.
'''
return '''This view is not exposed over CORS.'''
...which is rather interesting since I already have the root path (and others) exposed without any CORS decoration, and they are working fine from any origin. So it seems that there is something fundamentally wrong with this setup.
Along those lines, the tutorial here (https://blog.miguelgrinberg.com/post/designing-a-restful-api-with-python-and-flask) seems to indicate that Flask apis should naturally be exposed without protection (I would assume that's just since the CORS extension hasn't been applied), but my application is basically just operating like the CORS extension doesn't even exist (other than a few notes in the log that you can see).
EDIT 2:
My comments were unclear, so I created three example endpoints on AWS API Gateway with different CORS settings. They are GET method endpoints that simply return "success":
1) CORS not enabled (default):
Endpoint: https://t9is0yupn4.execute-api.us-east-1.amazonaws.com/prod/cors-default
Response:
XMLHttpRequest cannot load
https://t9is0yupn4.execute-api.us-east-1.amazonaws.com/prod/cors-default.
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://127.0.0.1:5000' is therefore not allowed
access. The response had HTTP status code 403.
2) CORS enabled - Origin Restricted:
Access-Control-Allow-Headers: 'Content-Type'
Access-Control-Allow-Origin: 'http://example.com'
Endpoint: https://t9is0yupn4.execute-api.us-east-1.amazonaws.com/prod/cors-enabled-example
Response:
XMLHttpRequest cannot load
https://t9is0yupn4.execute-api.us-east-1.amazonaws.com/prod/cors-enabled-example.
Response to preflight request doesn't pass access control check: The
'Access-Control-Allow-Origin' header has a value 'http://example.com'
that is not equal to the supplied origin. Origin
'http://127.0.0.1:5000' is therefore not allowed access.
3) CORS enabled - Origin Wildcard:
Access-Control-Allow-Headers: 'Content-Type'
Access-Control-Allow-Origin: '*'
Endpoint: https://t9is0yupn4.execute-api.us-east-1.amazonaws.com/prod/cors-enabled-wildcard
Response:
"success"
I'm not that experienced with infrastructure, but my expectation was that enabling the Flask CORS extension would cause my api endpoints to mimic this behavior depending on what I set at the origins= setting. What am I missing in this Flask setup?
SOLUTION EDIT:
Alright, so given that something on my end was obviously not normal, I stripped down my app and re-implemented some very basic APIs for each variation of CORS origin restriction. I've been using AWS's elastic beanstalk to host the test environment, so I re-uploaded those examples and ran a JS ajax request to each. It's now working.
I'm getting the Access-Control-Allow-Origin error on naked endpoints. It appears that when I configured the app for deployment I was uncommenting CORS(application, resources=r'/api/*'), which was obviously allowing all origins for the naked endpoints!
I'm not sure why my route with a specific restriction (origins=[]) was also allowing everything, but that must have been some type of typo or something small, because it's working now.
A special thanks to sideshowbarker for all the help!

From your question as-is, it’s not completely clear what behavior you’re expecting. But as far as how the CORS protocol works, it seems like your server is already behaving as expected.
Specifically, the curl response cited in the question shows this response header:
Access-Control-Allow-Origin: http://example.com
That indicates a server already configured to tell browsers, Only allow cross-origin requests from frontend JavaScript code running in browsers if code’s running at the origin http://example.com.
If the behavior you’re expecting is that the server will now refuse requests from non-browser clients such as curl, then CORS configuration on its own isn’t going to cause a server to do that.
The only thing a server does differently when you configure it with CORS support is just to send the Access-Control-Allow-Origin response header and other CORS response headers. That’s it.
Actual enforcement of CORS restrictions is done only by browsers, not by servers.
So no matter what server-side CORS configuration you make, the server still goes on accepting requests from all clients and origins it would otherwise; in other words, all clients from all origins still keep on getting responses from the server just as they would otherwise.
But browsers will only expose responses from cross-origin requests to frontend JavsScript code running at a particular origin if the server the request was sent to opts-in to permitting the request by responding with an Access-Control-Allow-Origin header that allows that origin.
That’s the only thing you can do using CORS configuration. You can’t make a server only accept and respond to requests from particular origins just by doing any server-side CORS configuration. To do that, you need to use something other than just CORS configuration.

Related

API giving CORS Error to the frontent even though it should allow it

I'm making an API with FastAPI, and the frontend is made with next.js, so when the nextjs application makes a post request to the API, it should return the data normally with no problem, but it keeps giving a CORS error, the cors in the API are:
origins = ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"]
)
and the cors error is
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://jc-api-test.herokuapp.com/users/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 500.
Since the error code is 500 - this is an internal server error, meaning something is wrong with your code. When a 500 error happens, the CORSMiddleware doesn't get to add any headers to the response, since an exception is thrown and regular request processing no longer happens.
Fix the error first (the log will show you what actually happens), then start debugging any CORS issues after that (see the other answers).
The client should be making an OPTIONS request before the POST. It's the server's response to that initial call that needs to have the Acces-Control-Allow-Origin header. Then also that header's value must match the client (that heroku domain in your error message). Make sure your server is handling that OPTIONS correctly and it should work.
Your allow_credentials setting breaks the setting.
As stated in FastAPI documentation, if allow_credentials is True, you must define some origins instead of ['*']:
allow_credentials - Indicate that cookies should be supported for cross-origin requests. Defaults to False. Also, allow_origins cannot be set to ['*'] for credentials to be allowed, origins must be specified.

FastAPI ignores CORS middleware [duplicate]

I'd like my Rails 5 API-only app, for now running on http://localhost:3000, to only accept requests from my NodeJS front-end app, for now running on http://localhost:8888.
So I configured /config/initializers/cors.rb like this:
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins "http://localhost:8888"
resource "*",
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head]
end
end
And I wrote this test:
#/spec/request/cors_request_spec.rb
RSpec.feature "CORS protection", type: :request do
it "should accept a request from a whitelisted domain" do
get "/api/v1/bodies.json", nil, "HTTP_ORIGIN": "http://localhost:8888"
expect(response.status).to eql(200)
end
it "should reject a request from a non-whitelisted domain" do
get "/api/v1/bodies.json", nil, "HTTP_ORIGIN": "https://foreign.domain"
expect(response.status).to eql(406)
end
end
The first test is passing as expected. But the second is failing with a response code of 200. Why?
(I'm not wed to a 406 response code by the way; just one that indicates the request will not be fulfilled.)
CORS configuration won’t prevent the server from accepting requests based on the value of the Origin request header. You can’t do that just through CORS configuration.
When you configure CORS support on a server, all that the server does differently is just to send the Access-Control-Allow-Origin response header and other CORS headers.
Enforcement of CORS restrictions is done only by browsers. It’s not enforced by servers.
CORS works like is: regardless of any CORS config you make on the server side, the server continues accepting requests from all clients and origins it otherwise would; and so all clients from all origins continue getting responses from the server just as they otherwise would.
So even when you see an error in browser devtools that a cross-origin request from your frontend JavaScript code failed, you’ll still be able to see the response in browser devtools.
But just because your browser can see the response doesn’t mean the browser will expose it to your frontend code. Browsers only expose responses for cross-origin requests to frontend code running at a particular origin if the server the request went to opts-in to allowing the request by responding with an Access-Control-Allow-Origin header which OKs that origin.
So for any requests with an Origin request header matching https://foreign.domain, the configuration snippet in the question should cause browsers to emit a message on the client side saying http://localhost:3000/api/v1/bodies.json can’t be loaded because there’s no Access-Control-Allow-Origin response header in the response (because your configuration causes the server to only send that header in responses to your whitelisted origins).
But that’s all you can do through CORS. You can’t prevent the server side from accepting and responding to requests from particular origins just by doing any CORS configuration on the server side. If you want to do that, you need to do it using something other than just CORS.

Flask-sentinel /oauth/token endpoint CORS issue

I'm having issues trying to get a token from my flask-sentinel app with my front-end.
To make the AJAX requests from my front-end to my Python Eve API server I use the superagent module.
While using a Basic Authentication I don't have any issue getting data from my endpoints. See code below:
superagent
.get( 'http://192.168.1.x:5000/endpoint' )
.auth( this.params.username, this.params.password )
.on( 'error', this.onError )
.then( this.onSuccess );
If I try to request a token to the /oauth/token endpoint with this code:
superagent
.post( 'http://192.168.1.x:5000/oauth/token' )
.set( 'Content-Type', 'application/x-www-form-urlencoded' )
.send( 'grant_type=password&client_id='+this.params.client_id+'&username='+this.params.username+'&password='+this.params.password )
.on( 'error', this.onError )
.then( this.onTokenReceived );
I get a CORS error:
Access to XMLHttpRequest at 'http://192.168.1.x:5000/oauth/token' from origin 'http://192.168.1.y:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Here are the settings of my application (omitting the database and domain settings):
SENTINEL_X_DOMAINS = ['http://192.168.1.y:3000']
SENTINEL_X_HEADERS = ['Authorization','Content-type','If-Match','Access-Control-Allow-Origin']
SENTINEL_X_EXPOSE_HEADERS = SENTINEL_X_HEADERS
SENTINEL_RESOURCE_METHODS = ['GET','HEAD','PUT','PATCH','POST','DELETE','OPTIONS']
SENTINEL_PUBLIC_METHODS = SENTINEL_RESOURCE_METHODS
SENTINEL_X_ALLOW_CREDENTIALS = True
X_DOMAINS = ['http://192.168.1.y:3000']
X_ALLOW_CREDENTIALS = True
X_HEADERS = ['Authorization','Content-type','If-Match','Access-Control-Allow-Origin']
RESOURCE_METHODS = ['GET','HEAD','PUT','PATCH','POST','DELETE','OPTIONS']
Can you please guide me in getting what I'm doing wrong?
Thank you in advance!
It's possible that because the content-type is not text/plain, the browser is issuing an OPTIONS request. and as stated in the console error the response does not set the 'Access-Control-Allow-Origin' header.
From looking at Eve's docs, it seems you need to set the X_EXPOSE_HEADERS variable with ['Access-Control-Allow-Origin'] that:
"Allows API maintainers to specify which headers are exposed within a
CORS response. Allowed values are: None or a list of headers names.
Defaults to None."
The browser expects to receive the 'Access-Control-Allow-Origin', thus the failure.
Try to allow this header in the response from the API
In your Flask app, try setting the 'Access-Control-Allow-Origin' header in your response, i.e.,
response.headers.add('Access-Control-Allow-Origin', '*')
That should most likely solve the issue.
I have sorted out how to fix this though I am not completely satisfied.
Here the steps I've followed:
I have forked the Flask Sentinel repository
I have installed Flas-CORS with Pip
I have edited the flask_sentinel/flask_sentinel.py file by importing flask_cors
Before this line I've inserted this piece of code:
CORS(app, origins=['http://192.168.1.y:3000','https://192.168.1.y:3000'])
I went back to my Eve project and installed Flask-Sentinel through my forked repository with Pip instead of the original one

Flask-CORS not working for POST, but working for GET

I'm running a Flask-Restful API locally and sending a POST request containing JSON from a different port. I'm getting the error
No 'Access-Control-Allow-Origin' header is present on the requested resource.
However, when I run
curl --include -X OPTIONS http://localhost:5000/api/comments/3
--header Access-Control-Request-Method:POST
--header Access-Control-Request-Headers:Content-Type
--header Origin:http://localhost:8080
I get
HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
Allow: HEAD, GET, POST, OPTIONS
Access-Control-Allow-Origin: http://localhost:8080
Access-Control-Allow-Methods: DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT
Vary: Origin
Access-Control-Allow-Headers: Content-Type
Content-Length: 0
which shows "Access-Control-Allow-Origin" as "*". GET works fine, it's just POST that gives this error. What could be going wrong? If relevant, for the frontend I'm using react and requesting through axios.
You have to add CORS(app, resources={r"/*": {"origins": "*"}}) into your flask app.
Hope that solves the issue.
the Flask-Cors docs explain why this might happen
"When using JSON cross origin, browsers will issue a pre-flight OPTIONS request for POST requests. In order for browsers to allow POST requests with a JSON content type, you must allow the Content-Type header. The simplest way to do this is to simply set the CORS_HEADERS configuration value on your application: e.g."
https://flask-cors.readthedocs.io/en/1.9.0/
app.config['CORS_HEADERS'] = 'Content-Type'
In my case, a CORS error raised because of an internal error. An error completely unrelated to CORS, which should return 500, was causing this.

Django view sending empty reply with proper headers

I have Django project on Dreamhost server which has several views that returns Json response.Yesterday I have ported my Django project from local machine(localhost) to dreamhost server running apache.Now if I call my django view through jquery for
http://www.abc.com/projects/
It should return me all projects that i have in my mongodb database but instead of that it returns :
On Firefox - just headers with no response
Connection Keep-Alive
Content-Type application/json
Date Thu, 19 Jan 2012 09:03:34 GMT
Keep-Alive timeout=2, max=100
Server Apache
Status 200 OK
Transfer-Encoding chunked
On Chrome - No headers and response data.It throws an error:
XMLHttpRequest cannot load http://abc.com/Projects/. Origin null is not allowed by Access-Control-Allow-Origin.**
If I just access the http://www.abc.com/projects/ through my web-browser it returns me results in json format,but not in case if I use JavaScript/Jquery.
Earlier I was using this middleware to allow other domains to request and get response on my local-machine with django in-built server.But now when I am running on apache server It stops working so I removed It from Settings.py file.
I don't know why is this error coming .Please help
*EDIT*
As #burhan suggested I used jsonp on client side and now my server is returning json but browser is giving error before parsing it.Error is : unexpected token
JSON i am getting in reply is :
{"projects": [{"projectName": "carmella", "projectId": "4f13c7475fcff30710000000"}, {"projectName": "SeaMonkey", "projectId": "4f1677b75fcff37c03000001"}]}
You are running into the same origin policy sandbox. Since your server is www.abc.com and you are accessing abc.com - the origin is not the same, which is why the script is not executing.
You have a few options:
Make sure the URL matches exactly - to avoid the same origin policy sandbox.
Use jsonp in your javascript libary.

Categories

Resources