JQuery AJAX with Rails’ authenticity token

In Ruby on Rails, authenticity tokens are generated to prevent CSRF (Cross Site Request Forgery) attacks. These tokens generate a unique “identifier” to prevent other website from making requests on your behalf, or so-called “session riding”.

In Ruby on Rails, to have this identifier available for you, you need to put <%= csrf_meta_tag %> in your view, usually in app/views/layouts/application.html.erb. This tag creates something like:

<meta name=”csrf-param” content=”authenticity_token”/>
<meta name=”csrf-token” content=”uDDuQj14CCJ…”>

If you create your own AJAX functions, say with JQuery, you would need these values in order to have rails handle your request. This can be done using the following:

var param = $(‘meta[name=csrf-token]‘).attr(‘content’);

Which you can use then in your AJAX requests

$.post(‘/post’, { body: $(‘#post_body’).val(), authenticity_token: param }, function(data){
var ret = jQuery.parseJSON(data);
if(ret.status==”ok”) {

2 Comments

  • February 7, 2011 - 8:27 pm | Permalink

    Correct:
    var token = $(‘meta[name=csrf-token]’).attr(‘content’);

  • February 9, 2011 - 12:11 pm | Permalink

    Hi Delta,

    Thank you for noticing my mistake, you are right. I mistyped the jquery selector.

    Thank you!
    Michael

  • Leave a Reply

    Your email address will not be published. Required fields are marked *