简体   繁体   English

如果调用是在AJAX中进行的,如何检测并仅允许特定的URL访问Flask API?

[英]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. 我已经为网站创建了Flask API,其中前端AJAX通过同一域上的POST请求调用API。

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. 但是该API不受保护,因为任何人都可以使用参数(在JS AJAX中可见)发出POST请求并获得响应。

I want to protect this by allowing only certain specific urls to access my Flask API. 我想通过仅允许某些特定的URL访问我的Flask API来保护这一点。 How should I do this in my Python code? 如何在我的Python代码中执行此操作?

EXAMPLE

Example Situation - Python 示例情况-Python

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

AJAX 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. 因此,这里https://www.example.com/是网站,GET请求在该网站上返回index.html页面。 But on POST request it return "This is post". 但是在POST请求中,它返回“ 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? 考虑到要从AJAX发起的POST请求,我应该如何只允许https://www.example.com/获得响应?

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: 例如,如果您选中request.host ,则用户可以使用Python Requests设置Host标头:

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

If you want to restrict who can access your API, you need to implement authentication. 如果要限制可以访问您的API,则需要实施身份验证。 But that still won't restrict how they can access it. 但仍然不会限制他们如何能够访问它。

You can check the request.host_url in the hook before_request : 您可以在before_request钩子中检查request.host_url

@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. 您可以使用Flask-Security保护您的API。 There is a tutorial about it. 有一个关于它的教程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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