Cookies vs. Sessions with CookieStore

In Rails 3, what is the difference between storing data in a cookie and storing data in a session with the session store set by default in CookieStore?

eg.

cookie[:foo] = 'bar' # MyApp::Application.config.session_store :cookie_store, key: '_myapp_session' session[:foo] = 'bar' 

As far as I can tell, both are ultimately stored in a client cookie.

When do you decide to use one over the other?

Thank.

+53
ruby-on-rails cookies ruby-on-rails-3 session
Feb 22 '13 at 10:53
source share
2 answers

The main difference is that when using cookie[:foo] = 'bar' user can see the value for the cookie, i.e. 'bar' . When you use session[:foo] = 'bar' , the value will be encrypted with rails and stored in the cookie _myapp_session .

You should use the cookie[] format when the information you want to save is not related to the session, for example. when users choose their preferred language.

You must use the session[] format if you want to save information related to the current session, for example. user id

+91
Mar 01 '13 at 9:01
source share

Rails provides several storage mechanisms for session hashes. The most important are ActiveRecord::SessionStore and ActionDispatch::Session::CookieStore .

There are several session stores, that is, where Rails stores the session hash and session identifier. Most real-time applications select ActiveRecord::SessionStore (or one of its derivatives) through the file vault for performance and maintenance reasons. ActiveRecord::SessionStore stores the session identifier and hash in the database table and stores and retrieves the hash for each request.

Rails 2 introduced the new default session store, CookieStore . CookieStore stores the session hash directly in the client-side cookie. The server retrieves the session hash from the cookie and eliminates the need for a session identifier. This will significantly increase the speed of the application, but this is a controversial storage option, and you should consider the consequences of its security:

Cookies imply a strict size limit of 4 KB. This is normal since you should not store large amounts of data in a session anyway, as described above. Saving the current user database identifier in a session is usually normal. The client can see everything that you store in the session, because it is stored in clear text (in fact, Base64 is encoded, therefore not encrypted). Therefore, of course, you do not want to keep any secrets here. To prevent session hash falsification, the digest is calculated from the server-side privacy session and inserted at the end of the cookie. This means that the security of this repository depends on this secret (and on the digest algorithm, which by default does not have SHA512, which has not yet been compromised). Therefore, do not use a trivial secret, i.e. Dictionary word, or less than 30 characters

+10
Feb 25 '13 at
source share



All Articles