Ajax and the Rails request authenticity token
Rails 1.2.6 introduced CSRF protection in the form of an authenticity token which is a reasonably long string used to make sure that any PUT / POST / DELETE request you've made to an application was really generated by you (or at least your browser) doing something in the application and that you weren't tricked into submitting it by some nefarious third party.
Rails automatically adds this token to any forms generated by it's helpers, but when building rich Ajax applications it can be useful to be able to generate the Javascript by hand.
Fire this snippet into your layout just above including all the other Javascript files to get access to the authenticity token in Javascript and let you submit requests using Ajax.
<%= javascript_tag "window._token = '#{form_authenticity_token}';" %>
Now you can build Ajax requests that are allowed to do stuff to the application.
new Ajax.Request('/foo.json', {
method: 'PUT',
parameters: {
authenticity_token: window._token,
text: $F('foo_text')
}
/* callbacks omitted for brevity */
})
curl -LO http://barkingiguana.com/2008/11/17/ajax-and-the-rails-request-authenticity-token.html.orig
curl -LO http://barkingiguana.com/2008/11/17/ajax-and-the-rails-request-authenticity-token.html.orig.asc
gpg --verify ajax-and-the-rails-request-authenticity-token.html.orig{.asc,}
If you'd like to have a conversation about this post, email craig@barkingiguana.com. I don't bite.