Search code examples
pythonflaskcorsflask-cors

Flask Cors not blocking requests from undesired origins


I'm testing out a flask REST api and I would like to restrict access to the api from all origins except for local development and a certain url once it's in production by using flask-cors. I thought setting the CORS_ORIGINS config would do the trick but it still allows requests to the api. I then tried the method shown here but I still get valid requests. The api is running on localhost:5000/api and I am opening up an http server separately using python3 -m http.server which is running on localhost:8000. When I use await fetch('http://localhost:5000') from the http server's developer tools console I still get valid requests, even though these should be blocked, correct?

from flask import Flask, jsonify
from flask_cors import CORS

cors = CORS()

def create_app():
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(CORS_ORIGINS="http://localhost:5000")
    cors.init_app(app, resources={"r/*": {"origins": "http://localhost:5000"}})
    
    @app.route('/api')
    def api():
        return jsonify({'success': "Healthy: OK"}), 201

    return app

Any ideas what I could be doing wrong? Or is there a better way to restrict access to my api so it is only available locally or from a specific domain?

Thanks!


Solution

  • The CORS is usually enforced by browsers. What it does is that it prevents your web page from making request and showing data from servers other than it originated from, except in case it is allowed in ALLOW_ORIGINS headers by the server. The problem you are facing is that you are unable to enforce CORS. I suspect that might be because you are using localhost. Because many browsers have relaxed SOPs for localhost in order to allow seamless development. You might have to deploy your server and web page on different servers in order to face CORS. I hope this is helpful