Search code examples
jqueryexpresshttp-postcsrfcompoundjs

How to post csrf-token to compoundjs using jquery


My csrf-token is rendered as a meta tag in my application layout

<meta content="authenticity_token" name="csrf-param">
<meta content="28c5136f4ef175c620ead78cc6d9589b98be0b78" name="csrf-token">

I write the content of the csrf-token meta tag to a configuration object and then I use ajaxPrefilter to add it whenever I do a post with jquery.

   $.ajaxPrefilter(function(options, originalOptions, jqXHR){
            if (options['type'].toLowerCase() === "post") {
                console.log("token got called" + configs.csrf_token);
                jqXHR.setRequestHeader('X-CSRFToken', configs.csrf_token);
            }
        });

However when I do a post as below

$.post( "/images/external/url", { url: url, 'csrf-param': configs.csrf_token})
    .done(function( data ) {
     console.log( "Data returned: " + data );
    });

I get a 403 with Incorrect authenticity token error back.

The csrf-param in the post is me trying to figure out if that had anything to do with it, as I understand it the X-CSRFToken request header should be the pertinent part?


Solution

  • Reading through csrf.js in connect I can see that the header is supposed to be X-CSRF-Token.