Read more

When sessions, cookies and Clearance tokens expire and how to change it

Henning Koch
September 10, 2010Software engineer at makandra GmbH

Expiration of Rails sessions

By default Rails sessions expire when the user closes her browser window.

Illustration money motivation

Opscomplete powered by makandra brand

Save money by migrating from AWS to our fully managed hosting in Germany.

  • Trusted by over 100 customers
  • Ready to use with Ruby, Node.js, PHP
  • Proactive management by operations experts
Read more Show archive.org snapshot

To change this edit your config/initializers/session_store.rb like this:

ActionController::Base.session = {
  :key          => '...',
  :secret       => '...'
  :expire_after => 10.years
}

In older Railses the initializer is not available. Set the option in the environment.rb instead:

config.action_controller.session = {
  :key          => '...',
  :secret       => '...'
  :expire_after => 10.years
}

Expiration of Rails cookies

In addition to the sessions hash there is also the cookies hash, which works differently in some aspects. Just use the session if you are uncertain about the differences.

Each cookie has its own expiration date, which can be set together with the cookie's value:

cookies[:token] = {
  :value   => user.secret_token,
  :expires => 1.year.from_now.utc # don't exceed year 2038 or it will raise an "undefined method `gmtime'" error
}

When you don't give an :expires options, the default is when the user closes her browser window (I believe).

Expiration of Clearance tokens

In recent versions of clearance, authentication tokens are stored in a cookie that expires after one year. There is no longer Show archive.org snapshot a "remember me" checkbox.

If you need to change the expiration date of your authentication tokens, you need to patch the sign_in method in the Clearance::Authentication module that is automatically included in all your controllers and helpers.

Older versions of Clearance had a "remember me" checkbox that changed how expiration dates where set. Even older versions of Clearance used the session instead of cookies. If you're working on a vintage project you'll need to dig into the Clearance code to find out what's going on and how to change it.

Posted by Henning Koch to makandra dev (2010-09-10 10:47)