Issue
I have built a get REST API in python with flask. I am calling this API from my own website and I would like to avoid other websites from using it.
To do that, in the header of the api definition I set
'Access-Control-Allow-Origin' = '****'
being **** the domain of the website allowed to make the call.
Is this enough to avoid others from using my api ?
Solution
A better way to do CORS in Flask
I would probably use Flask-CORS to add adaptable Cross Origin Resource Sharing capability to your Flask project...
First pip install Flask-CORS:
pip install -U flask-cors
and then implement inside your app instantiation:
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
cors = CORS(app, resources={r"/api/*": {"origins": "example.com"}})
This will allow access to that specific route from example.com only and deal with all the headers for you, similar to what Avian advised but in a Flasky kind of way. Of course if you want a specific origin (or indeed any origin) to have access to your full API (or part of your API) you can use wild cards.
Is this enough to avoid others from using my api?
No this will only stop people from accessing your API from some other website / origin using JS. It will not stop people simply directly accessing your API using CuRL or equivalent. If you want to prevent access to your API you should implement some form of token / key auth credentials to authenticate only those users you wish to gain access and return a "Unauthorized" 401 to any users without valid credentials.
Answered By - Robert Putt
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.