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 */
})

Related articles

Leave feedback...

  1. ******* “authenticity token” !
    Awesome tip ! Thanks.

Commenting is closed for this article.

About the boy

A picture of Craig in grayscale

Craig Webster is a software engineer living in London. He usually works with Ruby although sometimes he sneaks in some Erlang or JavaScript. He's into rock climbing, snowboarding, skating, photography and fencing. Yes, this does mean he has a sword.

Near here you'll find Craig's homepage, contact details, PGP key and keysigning policy, and talks.

Licence

The entire content of this blog is public domain. Use it however you fancy. You don't even need to attribute it to me, although it would be nice if you did. Just don't sue me and we'll all be happy.

I Work With Rails

Recommend Me

My Travels

I go places. Do you go places too? Let's meet up!.