0

I have a rails app and an api working together. The application has two years now and have been developped with the options (in application_controller):

skip_before_filter :verify_authenticity_token, :if => Proc.new { |c| c.request.format == 'application/json' }
#protect_from_forgery with: :null_session 

So there was no protection at all against CSRF.

I added <%= csrf_meta_tag %> on all my view layouts and and protect_from_forgery on my application_controller.

The problem is that when my main page is requested, some ajax are executed and they do not contain the CSRF header so I get logout immediately.

How can I introduce the CSRF protection in my app?

rolele
  • 781
  • 9
  • 24
  • possible duplicate of [WARNING: Can't verify CSRF token authenticity rails](http://stackoverflow.com/questions/7203304/warning-cant-verify-csrf-token-authenticity-rails) – Slicedpan Jan 14 '15 at 09:24

1 Answers1

0

You need to change your Ajax requests to include the CSRF token. You can configure all AJAX requests to send the token by default in jQuery using the following code

$("body").bind("ajaxSend", function(elm, xhr, s){
  if (s.type == "POST") {
    xhr.setRequestHeader('X-CSRF-Token', $('meta[name=csrf-token]').attr('content'));
  }
});

(Code taken from this question). Other JS frameworks probably have similar functionality.

Community
  • 1
  • 1
Slicedpan
  • 4,995
  • 2
  • 18
  • 33
  • Started writing this answer then realised there is an almost identical question [here](http://stackoverflow.com/questions/7203304/warning-cant-verify-csrf-token-authenticity-rails). Have flagged as a duplicate – Slicedpan Jan 14 '15 at 09:25
  • Great Slicedpan, thanks for your answer and sorry for the duplicate. I have seen other answers but did not really understand that I can add this code ones and have all my ajax request containing the header. So I need to add this code just after the script jquery tag on my pages – rolele Jan 14 '15 at 10:06