Zander Perry
Zander Perry

Reputation: 99

Rails - WARNING: Can't verify CSRF token authenticity

I'm using some javascript called jpegcam (with paperclip, following these directions) and on different occasions it's creating faulty CSRF tokens. This is the only place in application with this issue. The bad tokens have '+' characters in the middle.

This section in the JS is the problem webcam.set_api_url('<%= upload_users_path %>' + '?' + csrf_param + "=" + encodeURI(encodeURI(csrf_token)));

Warning messages:

Started POST "/users/upload?authenticity_token=N0x/rDOgyC6AutbXzx8sZXLwDnB9zQ+NwWefXTpiSfE=" for 127.0.0.1 at 2013- 06-04 01:06:34 -0400
...
Parameters: {"authenticity_token"=>"N0x/rDOgyC6AutbXzx8sZXLwDnB9zQ NwWefXTpiSfE="}
 WARNING: Can't verify CSRF token authenticity
...
Completed 401 Unauthorized in 15ms

JS (in page view) looks like this:

<script type="text/javascript">
function onload_complete(msg) {
    // fetch the CSRF meta tag data
    var csrf_param = $('meta[name=csrf-param]').attr('content');
    var csrf_token = $('meta[name=csrf-token]').attr('content');

    // reset the api URL appending the auth token parameter
    webcam.set_api_url('<%= upload_users_path %>' + '?' + csrf_param + "=" + encodeURI(encodeURI(csrf_token)));
}
...
</script>

Upvotes: 1

Views: 1644

Answers (2)

nishanthan
nishanthan

Reputation: 460

Add this code in your /application.js

$(function() {
  $.ajaxSetup({
    beforeSend: function ( xhr ) {
      xhr.setRequestHeader("Accept", "text/javascript") 
    }
  }
}

Hope it helps

Upvotes: 1

glorieux
glorieux

Reputation: 119

Try passing the csrf-token on the header of your request as X-CSRF-Token. request.setRequestHeader("X-CSRF-Token", csrf_token)
That did the trick the last time I had problems with CSRF

Upvotes: 1

Related Questions