0

I'm diving into Ruby on Rails and building a web game where the user has to answer a question. I'm handling all the answer verification logic in Javascript in the browser so that my server doesn't have to. When my javascript code verifies that the answer is correct, my Javascript code will send a request to my Rails server to let it know that the user answered the question correctly using something like...

$.ajax({
  type: 'POST',
  url: url,
  data: data,
  success: success,
  dataType: dataType
}); 

Since anyone can use a tool like curl to cheat and send a similar request, how can I ensure that the request is coming from the javascript in my Rails view?

Thanks so much in advance for your wisdom!

BeachRunnerFred
  • 18,070
  • 35
  • 139
  • 238

1 Answers1

2

Rails by default uses CSRF tags in forms to prevent request from external sources. Read this for more info about cross site request forgery.

Trent Earl
  • 3,517
  • 1
  • 15
  • 20
  • Thanks, peterpan! I read the document and I'm still a little confused with how this works. Since I'm not using a Rails form, and instead I'm using the $.ajax call shown in my question, does Rails somehow recognize the $.ajax call and attach the security token to it? – BeachRunnerFred Dec 01 '12 at 23:03
  • You can hook into all jQuery ajax calls and add the CSRF token to all ajax requests. see http://stackoverflow.com/questions/7270947/rails-3-1-csrf-ignored – Trent Earl Dec 01 '12 at 23:06