Content
A heads-up about cache configuration and CSRF tokens/422 error
Added by Matthew Trescott over 4 years ago
I spent some time debugging this bizarre issue and wanted to share what I learned. Of course it's my fault for not testing my changes right away (or else I would have guessed it sooner) but I thought it might be useful anyway.
I've been working on a manual installation of sorts (actually traditional RPM packages without Pkgr or Bundler. I will try to remember to post here when I've vetted the packages a bit more thoroughly and have some better documentation written in case anyone's interested.) Anyway, I set the Rails cache expiration time to zero seconds and started getting the dreaded 422 "Unable to verify Cross-Site Request Forgery token" error when I tried to log in. Also, my session cookie showed up in Chromium's info dialog but wasn't being sent. After a lot of head-scratching I realized that the session cookie was set with an expiration of the current time, which meant it expired immediately. But that was just the tip of the iceberg.
After stuffing a bunch of puts
statements into ActionController and things I discovered that the CSRF token that Rails "saved" in the session object didn't match the token that my browser was sending. I also noticed that ActionController is programmed to generate a new CSRF token when needed. When I read that the :cache_store
backend matches session expiration times to the cache expiration time, I guessed that there was something wrong with the cache configuration. I commented out the changes I made in configuration.yml
and that fixed it! I guess setting cache_expires_in_seconds
to 0 does not, in fact, make the cache never expire. Probably best not to touch that setting at all, since individual functions using the cache can set their own expiration times anyway.