views:

87

answers:

1

In an application I make I'm getting lots of these messages:

A ActionController::InvalidAuthenticityToken occurred in items#vote_up:
  ActionController::InvalidAuthenticityToken
  /var/lib/gems/1.8/gems/actionpack-2.3.4/lib/action_controller/request_forgery_protection.rb:79:in `verify_authenticity_token'

which I suspect it's happening because people spend a lot of time on that page without ever refreshing it (it uses ajax) and the tokens expire.

Is there a way to make those tokens live longer?

+2  A: 

There is no reason why a time limit would be causing this exception. The exception ActionController::InvalidAuthenticityToken is caused when the forgery protection token received in the request is different from what it should be.

Here is some code that you can add to your JavaScript to add in the correct forgery protection token:

$.ajax({
  url: url,
  data: {
    authenticity_token: <%= form_authenticity_token.to_json %>,
    ...
  }
});

This way, your token will be correct.

Josh
Do the tokens live forever? Otherwise, how long do they live? Where do you propose I should add that (I don't think I have a single line of JavaScript in the whole project).
J. Pablo Fernández
You said that the request was over AJAX? Otherwise, the form helpers in Rails automatically put the correct authenticity token in for you.
Josh
Josh, it's over AJAX, but using Rails helpers, so it has the correct token. Otherwise it would fail always, not one in a hundred times.
J. Pablo Fernández