lemmks
lemmks

Reputation: 73

Rails/Heroku/Cloudflare: Can't verify CSRF token authenticity after domain change

We have a Rails 5.2.3 app in production using Devise 4.6.2 and being deployed at Heroku. The app was using a domain example.com and everything was fine. Today we needed to change that domain to app.example.com (example.com is now a WordPress site) and now when we try to log into the app we're getting:

Can't verify CSRF token authenticity
Completed 422 Unprocessable Entity in 19ms
ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):
vendor/bundle/ruby/2.6.0/gems/actionpack-5.2.3/lib/action_controller/metal/request_forgery_protection.rb:211:in `handle_unverified_request'

One thing I've realized is that now our production app isn't setting the session cookie. Our staging app (which uses an example.herokuapp.com domain) sets a cookie named '_myapp_session' (and it's still working fine), while in our production app there's no cookie being set. While googling about this I've found some mentions to the session_store.rb config (we didn't even had this file), so I created the file in config/initializers and tried to set to our app.example.com domain and also to domain: :all, but it didn't seem to make any difference.

Rails.application.config.session_store :cookie_store, key: '_app_myapp_session', domain: :all

What I am missing here? Why would the domain change stop the app from creating the session cookie? Oh, and we're using Cloudflare as our DNS and its __cfduid cookie is being correctly set. Could that be related?

Upvotes: 3

Views: 1325

Answers (2)

AC de Souza
AC de Souza

Reputation: 61

Did you read this post about Cloudflare cached pages and CSRF?

Poor tl;dr: If you cache a page with a CSRF protected form you have to update de CSRF using Ajax.

https://blog.cloudflare.com/the-curious-case-of-caching-csrf-tokens/

Upvotes: 1

lemmks
lemmks

Reputation: 73

So, apparently it was indeed related to Cloudflare. Our app.example.com entry on Cloudflare's DNS was "proxied" and once I've set it to "DNS only" and waited a few minutes our session cookies started appearing again.

I've just now realized that Cloudflare has its own cache, so I've purged that and will try to use the "proxied" setting again, but if that doesn't work I'll just use it as DNS.

If someone has details on why Cloudflare's proxied setting would stop the cookies from being set, please let me know. Thanks!

Upvotes: 3

Related Questions