简体   繁体   中英

How to detect and allow only specific urls to access Flask API, if the call is made in AJAX?

I've created a flask API as for a website, in which the front-end AJAX calls the API through a POST request on the same domain.

But the API is not protected as anyone can hit a POST request with parameters(which are visible in the JS AJAX) and get a response.

I want to protect this by allowing only certain specific urls to access my Flask API. How should I do this in my Python code?

EXAMPLE

Example Situation - Python

@app.route('/', methods=['GET','POST']) 
def post():
    if request.method == 'POST':
        return "This is Post"
    return render_template("index.html")

AJAX

$.ajax({
type: 'POST', 
url: "https://www.example.com/",
//Something ....

So here https://www.example.com/ is the site, the site on which GET request returns the index.html page. But on POST request it return "This is post". Considering the POST request to be initiated from AJAX, how should I allow only https://www.example.com/ to get the response?

Thanks

There is no way to require that a page is accessed with a specific client or from a specific location. All information that would indicate that can easily be set to whatever value you look for. For example, if you checked request.host , a user can use Python Requests to set the Host header:

requests.get('http://localhost:5000', headers={'Host': 'example.com'})

If you want to restrict who can access your API, you need to implement authentication. But that still won't restrict how they can access it.

You can check the request.host_url in the hook before_request :

@app.before_request
def check():
    if request.host_url != "http://www.example.com/"
        abort(401)

And you can use Flask-Security to protect your API. There is a tutorial about it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM