Csrf mismatch on load balancing

Hi everyone. My current CakePHP website is hosted by AWS and everything is going well, except when the server auto scales and some token mismatches start coming up. My current sessions is configured to “Cake”, and check tmp/sessions I can see several sessions being created there.

When I try to replicate locally using a single server instance, I try and delete the tmp/sessions entries but the Csrf exception doesn’t get thrown, I see other odd behavior in the site from the missing session information, but no issue with the Csrf.

I’m using the Csrf component, not the middleware.

Any feedback is greatly appreciated. Thanks

If you’re running multiple servers, you need to be saving sessions in the database, not the filesystem.

Also, look into the “sticky sessions” setting on your load balancer.

Sessions stored in files are locale to that file-system and therefore that machine. If your load-balancer switches over to another machine, the session isn’t available there anymore. You need a global session storage available to all your machines (see Zuluru’s answer) or implement a stateless system e.g. with JWTs.

In order to get you started out a little bit, have a look here :slight_smile:

Depending on how you have designed your stack, you might want to use something like Redis (or since you’re on AWS, ElastiCache), but you’ll need to write your own handler for it (though plugins that do this might already exist).
I personally do prefer Redis over the database (I use MySQL a lot so your mileage may vary depending on the database software you use) as it keeps my database cleaner, puts less load on my database (especially on the disks, which can be helpful when having a sudden spike of database queries) and can also be used for other things (like Caching).