如何在AJAX中使用Flask-WTForms CSRF保护? [英] How to use Flask-WTForms CSRF protection with AJAX?

查看:59
本文介绍了如何在AJAX中使用Flask-WTForms CSRF保护?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Flask-WTForms提供CSRF保护。使用普通的HTML表单时,它的效果很好,但是使用AJAX时,过程不清楚。我在表单中上传了文件,并使用AJAX将流程分为两部分:文件转到 upload 端点,而表单的其余部分转到提交端点。由于该文件是使用AJAX发布的,因此它没有获得CSRF令牌,但是我想保护 upload 端点免受攻击。使用AJAX时如何生成CSRF令牌?

Flask-WTForms provides CSRF protection. It works great when using normal HTML forms, but the process is less clear when using 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. Since the file is posted with AJAX, it doesn't get a CSRF token, but I want to protect the upload endpoint from attacks. How can I generate a CSRF token when using AJAX?

@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?


推荐答案

文档谈及有关AJAX实施CSRF保护的问题。

The documentation speaks a bit about implementing CSRF protection with regards to AJAX.

您可以启用模块:

from flask_wtf.csrf import CsrfProtect

CsrfProtect(app)

,然后在您的AJAX POST调用中使用它:

and then use this in your AJAX POST call:

<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)
        }
    }
})

希望这会有所帮助!

这篇关于如何在AJAX中使用Flask-WTForms CSRF保护?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆