R – In Rails, with cookie-based session store, are session and cookies the same thing


I've always been using the cookie-based session store, and never even knew about Cookies until now. So is there any situation where I'd need the cookies hash?

Best Solution

The cookies hash definitely has value in Rails apps. You should use cookies to store values on the client side that you want to remember between sessions.

A 'remember me' token is a great example. If you want to allow a user to be auto logged in when they visit your site, just store a persistent cookie with some user tamper-proof value (like a unique hash or guid (good) that maps to that user's row in your db but isn't hackable like just using a plain old integer user id (bad)). Then, when a user visits your site, you can check the cookies hash for a remember me token and, if found, do a lookup in your db and log the user in if a match is found. This is a very common practice.

If you need/want to store plaintext values in the client side cookie, but don't want the user to be able to futz with the values, just store a hash of that value in a companion cookie and salt the hash with some value unknown to the user. Then you just need to compute the salted hash of the plaintext value received from the client cookie and compare it against the hashed value also passed from the client cookie. If they match, you can trust it.