Sails.js CSRF token always changing for POST request

37 Views Asked by At

I have enabled csrf protection for my sails.js app and am calling the route to get the token for my POST request. However I keep getting a mismatch error for the post request.

This is my code to get the token just before the POST request

        jQuery.get("/csrfToken")
        .done(function (oData) {           
          console.log("CSRF Token: " + oData._csrf);
          $.ajax({
            url: sUrl,
            data: formData,
            headers: {
              'X-CSRF-Token': oData._csrf
            },
            processData: false,
            contentType: false,
            type: 'POST',
            success: function (data) {
              resolve(data);                
              console.log("upload success");
            },
            error: function (oError) {
              console.log("upload Error" + oError);
              reject(oError);
            }
          });

        })
        .fail(function (oError) {
          reject({
            message: "An error occurred requesting csrf:" + oError
          });

When I debug the route I am calling for the post request and compare req.csrfToken() against req.headers["x-csrf-token"] they are both different. Any suggestions on where I am going wrong? Thanks

1

There are 1 best solutions below

0
NeoNexus DeMortis On

I would recommend checking out how I am handling CSRF tokens.

I've disabled the built-in CSRF handler in the .sailsrc: https://github.com/neonexus/sails-react-bootstrap-webpack/blob/release/.sailsrc

This custom OK response is where most of the automated magic starts: https://github.com/neonexus/sails-react-bootstrap-webpack/blob/release/api/responses/ok.js

The isLoggedIn policy validates the CSRF token when needed: https://github.com/neonexus/sails-react-bootstrap-webpack/blob/release/api/policies/isLoggedIn.js

This helper generates a new token/secret: https://github.com/neonexus/sails-react-bootstrap-webpack/blob/release/api/helpers/generate-csrf-token-and-secret.js

This helper updates a req object with the new CSRF token (and updates session expiry): https://github.com/neonexus/sails-react-bootstrap-webpack/blob/release/api/helpers/update-csrf-and-expiry.js