Signed and Permanent cookies in Rails 3
Published over 5 years ago

David added a very cool feature to Rails recently – Signed cookies and permanent cookies This lets you set permanent and/or signed cookies very easily.

Before this, you’d have to write :

cookies[:user_preference] = {
  :value => @current_user.preferences,
  :expires => 20.years.from_now.utc

Now just becomes :

cookies.permanent[:user_preference] = @current_user.preferences

In case you happen to have seen my Railssummit presentation I had talked about using ActiveSupport::MessageVerifier for implementing “Remember me” functionality. The above commit makes that a whole lot easier.

In your model User.rb :

# User.rb
def self.authenticated_with_token(id, stored_salt)
  u = find_by_id(user_id)
  u && u.salt == stored_salt ? u : nil

And when the user checks “Remember me” box, make sure the following gets run :

cookies.permanent.signed[:remember_me] = [, current_user.salt]

This will set a permanent and signed cookie using the secret specified in ActionController::Base.cookie_verifier_secret. If you don’t have the cookie_verifier_secret defined, you might want to do that in one of the initializers.

Now when you want to login using the cookie :

user = User.authenticated_with_token(*cookies.signed[:remember_me])

In this specific case, it’s very important to use the salt in the cookie value. That makes sure the cookie gets invalidated if the user changes his password.