3

I'm trying to enable CORS in my Flask app, but it seems I can always access my urls from the browser whatever I put in the origins.

I don't know what I do wrong. Here's my code

from flask import Flask, jsonify
from flask_cors import CORS

app = Flask(__name__)
CORS(app, resources={r'/*': {'origins': 'www.examplesite.com'}})

@app.route('/reports', methods=['GET', 'POST'])
def index(id=None):
    return jsonify(success=True), 200 
Joern Boegeholz
  • 425
  • 1
  • 7
  • 21
Khaled Karam
  • 173
  • 3
  • 13
  • You mean you are trying to access it from a url other than www.examplesite.com? – Sam Jan 13 '16 at 21:36
  • Yup, and it works. it seems that my CORS configuration has no effect – Khaled Karam Jan 14 '16 at 01:56
  • Can you tell exactly what are you doing? What is the endpoint you are accessing and from which domain and how? – Sam Jan 14 '16 at 07:54
  • I'm trying to access an API only from specific domain to add some security. But doesn't seem to work. And I can access it locally with no problem. I deployed it then tried again from my browser and it also worked. it seems the CORS restore to '*' which is the default. – Khaled Karam Jan 14 '16 at 07:58

1 Answers1

0

You have two issues:

  1. The key provided to resources must be a valid Python regular expression, according to Flask-CORS documentation - use /.* instead of /* to match anything under the root /, rather than any path which consists only of slashes (which is what /* means).
  2. The origin returned should be a fully-qualified URI matching the syntax described in RFC 6454 Section 7.1, as per the W3C's specification for CORS. www.example.com is not a fully-qualified URI as it does not have a scheme. Use https://www.example.com or http://www.example.com instead. Alternatively you can use a regular expression to tell Flask-CORS to match both with only one entry in origins.
Sean Vieira
  • 140,251
  • 31
  • 286
  • 277