Cookies and sessions in Rails 2.0

Share this article

As we know, HTTP – the protocol that the web is built on is stateless – meaning that every transaction with the server doesn’t know anything about the previous transactions. To get around this, we use cookies to track session and emulate statefulness. Basically a cookie is stored on the users computer, which provides a key that the server can use to retrieve any session information.

In previous versions of Rails, we had a number of choices for our session stores – PStore, ActiveRecordStore, DRbStore and MemoryStore. PStore was always the default, which stored session data in a temporary file. This scheme did have a number of limitations such as race conditions in certain situations (That is, if two instances tried to write to the same session at the same time, your data could be come clobbered – storing a large information from an number of AJAX calls is one cause) as well as scaling issues – running multiple servers is pretty well impossible using PStore.

As a result most production systems would use one of the other stores, notably ActiveRecordStore which stores all of the session data in the system database.

To get around these limitations in PStore, Rails 2.0 will be introducing a new default store: CookieStore which stores all session information in one or more cookies on the clients computer. For anyone giving this a cursory glance, this may seem like a security risk, and it could be – however there are a few things you can do as a developer to make the process much more secure.

First of all, let me point out that the the store isn’t stored in plain text – there is a new forgery key in the environment.rb file, which you should set to a long, random string. The session information is hashed against this key, so the server can check for forgery attempts. So the first step is to ensure that this key is suitably long and suitably random.

Secondly, don’t store sensitive information in the session hash. Most application can get away with only storing a user id. This is a best practice thing – and isn’t just Rails-centric.

Thirdly, if you are especially paranoid, look at one of the other session store options. CookieStore really is the lowest-common denominator option, and one of the other store types would probably be more suitable for production systems anyway. You can see descriptions of the other store types on Scott Barron’s blog. He also benchmarks the different types of stores (Note though that as the article is quite old now, the new Cookie Store isn’t included in the benchmarks).

Myles EftosMyles Eftos
View Author

Myles a Perth-based web developer who has worked in all the major web languages, his weapon of choice being Ruby on Rails—although he’s found himself doing more and more front-end development in JavaScript, HTML, and CSS.

Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week