Rails 4 Security for Session Cookies

Rails 4 session cookies are now encrypted, and they use the EncryptedCookieStore class for storing session data. Encrypted cookie data is difficult to alter or even read by attackers.

Cookie Monster

Projects generated with Rails 3 use a different, digitally signed cookie as the default store for sessions. Those are also difficult to alter, but easier to read from. Aside from EncryptedCookieStore, Rails 4 also offers a type of cookie store to help you transition from digitally signed to encrypted cookies. It is called UpgradeSignatureToEncryptionCookieStore.

In order to use this undoubtedly descriptive cookie store, set session_store type to :upgrade_signature_to_encryption_cookie_store in your config/initializers/session_store.rb file.

Then, run rake secret from the terminal to generate a secure key. Using that secure key, add Myapp::Application.config.secret_key_base = <your_key> in your config/initializers/secret_token.rb, but do not remove the existing Myapp::Application.config.secret_token line.

By doing this, all previous digitally signed sessions will still be valid and will automatically be upgraded; new sessions will be created already with encryption.

If you happen to share your code publicly, make sure your secret_key_base value is kept private.

For more information on upgrading from Rails 3 digitally signed cookies to Rails 4 encrypted cookies, please check out the Rails Edge upgrade guides

UPDATE 2013-05-08: With the release of Rails 4.0.0.rc1, the upgrade_signature_to_encryption_cookie_store session_store type has been removed. Now, by simply setting values for both secret_key_base and secret_token, Rails will automatically upgrade existing signed cookie-based sessions to be encrypted.

- Caike Souza


01.28.13 ← See All Posts
blog comments powered by Disqus