4

After upgrading our application to Rails 6 and using all of the default configuration settings (which include per-form CSRF tokens), I'm seeing that sometimes users receive ActionController::InvalidAuthenticityToken, however the form has the authenticity_token in its params when looking at the stack trace, it's just different than the session's _csrf_token attribute at the time. I can't reproduce it myself, but it's happening enough in our error monitoring tool that I'd like to correct it.

We aren't doing anything custom with the session configuration (as a matter of fact, we aren't doing any initializer for sessions at all), so I'm curious what would cause the session's token to not match the form's?

trevorhinesley
  • 845
  • 1
  • 10
  • 36
  • Is your session sticking properly? It's possible that it's being recreated each time. Check by looking at `session.id`. – tadman Feb 17 '20 at 22:25
  • Caching is one really common cause. If you have a reverse proxy in front of your server it will serve the same form (and thus the same CSRF token) to all the incoming requests. – max Feb 17 '20 at 22:31
  • @max is that possible if I can't reproduce it? Would it be the reverse proxy's fault (in our case, load balancer--HAProxy) if it's not happening to everyone? – trevorhinesley Feb 17 '20 at 23:38
  • @tadman same as above -- is it possible that's the case if it's not reproducible? – trevorhinesley Feb 17 '20 at 23:38
  • Try eliminating variables to see what happens. Go direct bypassing the proxy, etc. – tadman Feb 17 '20 at 23:41
  • @trevorhinesley I actually don't know, its not really my area expertise. Its is something that has burned me in the past though. – max Feb 17 '20 at 23:44
  • @tadman confirmed that our proxy has the appropriate X-Forwarded-* headers, so it must be something unrelated... – trevorhinesley Feb 18 '20 at 01:36
  • That's unrelated. You should be paying attention to `session.id` and in particular if the cookie is being accepted. A mismatched domain will cause cookie rejection and the session won't stick, so you'll get a new one on each request. – tadman Feb 18 '20 at 02:18
  • @tadman got it. But how would I go about checking if the cookie is being “accepted”? – trevorhinesley Feb 19 '20 at 13:29

0 Answers0