2

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.

Zoyd
  • 3,449
  • 1
  • 18
  • 27
  • It's really hard to tell what you could have done wrong, without seeing what you've done. – sevenseacat Dec 27 '15 at 09:05
  • I followed the instructions in the blog post I mentioned. Apart from that, I did nothing related to sessions or authentication. Actually, if someone could just confirm that what I am experiencing is not the expected behaviour, that would already be useful. – Zoyd Dec 27 '15 at 09:11
  • Maybe the same answer for this question? https://stackoverflow.com/questions/50159847/single-page-application-and-csrf-token –  May 06 '18 at 23:52

1 Answers1

4

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.

Zoyd
  • 3,449
  • 1
  • 18
  • 27
  • Maybe the same answer for this question? https://stackoverflow.com/questions/50159847/single-page-application-and-csrf-token –  May 06 '18 at 23:52