Implementation of "Remember Me" in a Rails Application

Implementation of Remember me in a Rails application

I have spent a while thinking about this and came to some conclusions. Rails session cookies are tamper-proof by default, so you really don't have to worry about a cookie being modified on the client end.

Here is what I've done:

  • Session cookie is set to be long-lived (6 months or so)
  • Inside the session store

    • An 'expires on' date that is set to login + 24 hours
    • user id
    • Authenticated = true so I can allow for anonymous user sesssions (not dangerous because of the cookie tamper protection)
  • I add a before_filter in the Application Controller that checks the 'expires on' part of the session.

When the user checks the "Remember Me" box, I just set the session[:expireson] date to be login + 2 weeks. No one can steal the cookie and stay logged in forever or masquerade as another user because the rails session cookie is tamper-proof.

How to implement a Remember Me function in Rails 3?

Have been reading the Rails tutorial book and it has an implementation for Remember Me

You can check for some hints (The implementation may be different from yours)

http://ruby.railstutorial.org/book/ruby-on-rails-tutorial#sec:remember_me

Remember me option - how do I implement it?

The way I've done it is this (we're using OmniAuth for the authentication and Mongoid for user storage - the login form uses AJAX so the reply is JSON). The HTML field that corresponds to the "Remember me" checkbox is called "remember":

post '/auth/identity/callback' do
u = User.find(env['omniauth.auth']['uid'])
session[:user] = u
session.options[:expire_after] = 2592000 unless params['remember'].nil? # 30 days
[200, {:msg => 'User logged in'}.to_json]
end

The key here is the sessions.options[:expire_after] line. If you don't set :expire_after, the cookie will be automatically deleted when the browser quits. Once you set it, the cookie becomes persisten across browser restarts, and is kept for the number of seconds specified.

remember_me with warden

Devise, which is an authentication solution on top of Warden, has a rememberable implementation.



Related Topics



Leave a reply



Submit