Search code examples
ruby-on-rails-3.2csrfauthenticity-token

CSRF Token Session gets reset


I'm using Rails 3.2.3 along with the active_record_store for my session.

What I understand is that the CSRF token in rails is stored in a session and should not be reset unless reset_session is called or for some reason the session is destroyed.

But at certain places when remote form loads via ajax it contains a different authenticity token from that specified in the META tag on that page. Hence causing a invalid token error and reset_session on the submission of that form.

def form_authenticity_token
  session[:_csrf_token] ||= SecureRandom.base64(32)
end

I am not able to figure of for a valid on going session why session[:_csrf_token] is getting destroyed and creating a new token?


Solution

  • After a lot of hunting, finally figured out this issue. I was storing model objects directly in the session and though even after using a active record session store which has a size limit of 65KB, yet the session got truncate after 4kb, that was causing the CRSF token to get erased and a new one generated. Yeah! Blunder... Never store model objects in the session unless you have a very good reason to do otherwise. Anyways still trying to figure out why even after have a active record session store I was not able to store a larger object in the session.