RoR + Devise: CSRF token changes at every request

≯℡__Kan透↙ 提交于 2019-12-07 22:48:06

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/34479006/ror-devise-csrf-token-changes-at-every-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!