简体   繁体   English

如何在AJAX中使用Flask-WTForms CSRF保护?

[英]How to use Flask-WTForms CSRF protection with AJAX?

Flask-WTForms provides CSRF protection. Flask-WTForms提供CSRF保护。 It works great when using normal HTML forms, but the process is less clear when using AJAX. 使用普通HTML表单时效果很好,但使用AJAX时过程不太清楚。 I have a file upload in my form, and I split the process in two with AJAX: the file goes to the upload endpoint while the rest of the form goes to the submit endpoint. 我在我的表单中有一个文件上传,我用AJAX将进程分成两部分:文件进入upload终点,而表单的其余部分进入submit端点。 Since the file is posted with AJAX, it doesn't get a CSRF token, but I want to protect the upload endpoint from attacks. 由于文件是使用AJAX发布的,因此它不会获得CSRF令牌,但我希望保护上upload端点免受攻击。 How can I generate a CSRF token when using AJAX? 如何在使用AJAX时生成CSRF令牌?

@app.route('/submit', methods=["GET","POST"])
@login_required
def submit():
    form = MyForm()

    if request.method == "POST" and form.validate():
        # success, csrf checks out and data is validated
        # do stuff

    csrf_for_uploads = # generate csrf?
    return render_template('some_form.html', form=form, csrf_for_uploads=csrf_for_uploads)

@app.route('/upload', methods=["POST"])
@login_required
def upload():
    myfile = request.files['file']
    # How do I verify CSRF now?

The documentation speaks a bit about implementing CSRF protection with regards to AJAX. 文档说明了关于实现AJAX的CSRF保护。

You can enable the module: 您可以启用该模块:

from flask_wtf.csrf import CsrfProtect

CsrfProtect(app)

and then use this in your AJAX POST call: 然后在你的AJAX POST调用中使用它:

<meta name="csrf-token" content="{{ csrf_token() }}">

var csrftoken = $('meta[name=csrf-token]').attr('content')

$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken)
        }
    }
})

Hope this helps! 希望这可以帮助!

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

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