Search code examples
ajaxruby-on-rails-4devisecsrf-protection

RoR + Devise: CSRF token changes at every request


I am using Devise to handle authentification in a web application, and I set it up to work with Ajax as explained on this blog post. It works fine, I can sign in and out. However, there is an anomaly: the CSRF token is regenerated at every request. This happens whether the user is signed in or not, and even if the request is a GET, although I keep reading everywhere that the token should not change during a session. This forces me to add a mechanism to update the token on the client, since it is not done automatically because I use Ajax. Could someone tell me if this has somehow become the new default, or if not, what I could possibly have done wrong?

Versions used: Rails 4.2.5, Ruby 2.2.4, Devise 3.5.3.


Solution

  • I finally figured it out.

    I used the code provided in the above blog post to get the CSRF token by calling form_authenticity_token. As I finally found out, Rails 4.2.1 introduced a new implementation that calls masked_authenticity_token, which is why I thought the token was being reset. In fact it was not, only a randomly masked version of it was sent. This is clear in the source history. One can get the actual token in current Rails version like so: session[:_csrf_token]. This can be useful to check that the token does not change when it should not, which is what I was trying to do.

    I hope this answer can be useful to someone. It certainly took me time to find it.