Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3.1 - CSRF ignored?

here my problem,

I've got a rails 3.1 app and I'm trying to make an ajax request but I get the warning message "WARNING: Can't verify CSRF token authenticity"…

Inside my layout I've got the helper method "csrf_method_tag", and I add the following javascript code (don't know if it's really required or not):

$.ajaxSetup({
  beforeSend: function(xhr) {
    xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
  }
});

My Gemfile contains the gem jquery-rails (>= 1.0.12) and I require jquery & jquery-ujs at the top of my application.js.

Even with that, the message still appears. Did i forget something?

Thanks for you help.

like image 824
K'ao Avatar asked Sep 01 '11 13:09

K'ao


1 Answers

I had this exact same trouble. I was trying to catch a javascript event (you_tube player completed) and Ajax back to my server to let me know. I was getting:

WARNING: Can't verify CSRF token authenticity

whenever the jQuery ajax call hit my server. I added your code fix above

$.ajaxSetup({
    beforeSend: function(xhr) {
        xhr.setRequestHeader('X-CSRF-Token',
                             $('meta[name="csrf-token"]').attr('content'));
    }
});

and it works fine. I think the only difference is in my layout I have

<%= csrf_meta_tags %>

and not csrf_method_tag as you mentioned in your original post.
So thank you for the fix, it was in the original post.

like image 141
Mike Vargo Avatar answered Nov 03 '22 02:11

Mike Vargo