Flask-wtf: csrf_token is removed from session before I can POST my form

I am using Flask with Flask-Security (specifically Flask-WTF regarding my csrf problem) to "ease" the process of logging / loggin-users (not that easy yet). I am using BackboneJS on the front end, so I kind of hacked the original way of using Flask-WTF. Indeed, I am making an AJAX GET request to / register to get the registration page (generated by Flask-Security), and I put the resulting HTML into the modal.

render: function () {
            var self = this;
            $.ajax({
                type: 'GET',
                url: Config.constants.serverGateway + "/register"
            }).done(function(result){
                console.log("get register done", result);
                var html = self.template({ config: Config, form: result });
                self.$el.html(html);
            }).fail(function(error){
                console.log("Could not get register token", error);
                var html = this.errorTemplate({ config: Config });
                self.$el.html(html);
            });

            return this;
        }

      

This way I have a generated csrf and when I submit the credentials I am sending the correct csrf on the user data (email and password).

submit: function () {
            console.log("submit");
            var self = this;
            var formData = this.$el.find('form').serialize();
            $.ajax({
                type: 'POST',
                url: Config.constants.serverGateway + "/register",
                data: formData,
                dataType: 'json'
            }).done(function(result){
                self.trigger('close');
            }).fail(function(error){
                console.log("Could not submit register data", error);
            });
        }

      

On the server side, I can debug my Python code to see that the csrf_token that was generated when I requested the registration page disappeared from the session object, resulting in a new one being generated, which of course does not match the one I am sending with my form. The session is still the same, though, as the _id is the same during GET and POST.

You can see the code in flask_wtf / csrf.py :: generate_csrf () which is called when the form object is created in the :: register function from flask_security / views.py

if 'csrf_token' not in session:
    session['csrf_token'] = hashlib.sha1(os.urandom(64)).hexdigest()

      

This results in a CSRF TOKEN MISSING error.

Additional information is that my interface and delivery servers come from the same server as they have a different port number.

Finally, when I use the href on the front-end and render the page returned by the server on a "GET" request, the form submission works well. I just like to display this registration form in a modal format.

thanks for the help

+3


source to share


2 answers


Ok, I finally figured out the solution to my problem. I feel like a noob (what I am).

The problem has to do with session credentials not being sent to the server with requests so that the server doesn't access the session cookie. I found a solution in the following tutorial: http://backbonetutorials.com/cross-domain-sessions/ To submit it, I added the following lines in my Backbone router initialization function:



// Use withCredentials to send the server cookies
// The server must allow this through response headers
$.ajaxPrefilter( function( options, originalOptions, jqXHR ) {
    options.xhrFields = {
        withCredentials: true
    };
});

      

This means that all AJAX requests include withCredentials = true

. On the server side, I had to install Access-Control-Allow-Credentials:true

. Since I am using flask-cors this is done via [supports_credentials=True][2]

CORS object creation.

+1


source


(I am answering here as I cannot comment) @junnytony Yes, I have a token in my module and I am sending it in my POSt request. When I debug my Flask application, I can see the toekn that I sent with my POST request, the problem is that it should be compared with the one that should be checked, but the one that was in the session is gone, so the checkbox is wtf lib generates a new one, which crashes when comparing to the one I posted.



0


source







All Articles