Ajax and the Rails Request Authenticity Token

November 17, 2008 · 1 min read

Rails 1.2.6 introduced CSRF protection in the form of an authenticity token -- a reasonably long string that ensures any PUT, POST, or DELETE request to your application was genuinely triggered by you (or at least your browser) and not by some nefarious third party.

Rails automatically adds this token to any form generated by its helpers. But when you're building rich Ajax interactions, you sometimes need to construct the requests by hand.

Drop this snippet into your layout, just above where you include the rest of your JavaScript files, and you'll have the authenticity token available from JavaScript:

<%= javascript_tag "window._token = '#{form_authenticity_token}';" %>

Now you can build Ajax requests that the application will actually accept:

new Ajax.Request('/foo.json', {
  method: 'PUT',
  parameters: {
    authenticity_token: window._token,
    text: $F('foo_text')
  }
  /* callbacks omitted for brevity */
})