Skip to content Skip to sidebar Skip to footer

How To Use Flask-wtforms Csrf Protection With Ajax?

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 t

Solution 1:

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

You can enable the module:

from flask_wtf.csrf import CsrfProtect

CsrfProtect(app)

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

Hope this helps!

Solution 2:

Im thinking !/^ is a negative assertion so if the request is not matching Get/Head etc and not cross domain, then set request header with the value of the csrf token

Post a Comment for "How To Use Flask-wtforms Csrf Protection With Ajax?"