restful-authentication + subdomain-fu = needing cookie adjustments

I’ve perused several posts about handling cookies when multiple subdomains are involved however, the solutions were either for older versions of rails or didn’t resolve my situation; we wanted to have a cookie which could be used among all subdomains. This might also give you some insight as to why restful-authentication doesn’t have a feature to do all this for you — it keeps changing and by-hand is best for now. If you’re employing this, do be diligent with security; sharing credentials across domains can be risky business if your security varies across domains.

To do this, first edit config/initializers/session_store.rb where you’ll want to add the key:

:domain => ‘.example.com’

The format here is important – if you don’t prefix the domain with a period the cookie (and session) will not apply for requests to subdomains. This covers the rails session — however we also need to cover the cookie set by restful-authentication which you’ll find in lib/authenticated_system.rb. In the kill_remember_cookie! and send_remember_cookie! methods insert same key as above or a reference to the session_options key. It’ll look like this:

def kill_remember_cookie!
  cookies.delete :auth_token, :domain => ActionController::Base.session_options[:domain]
end
def send_remember_cookie!
  cookies[:auth_token] = {
    :value   => @current_user.remember_token,
    :expires => @current_user.remember_token_expires_at,
    :domain => ActionController::Base.session_options[:domain] }
end

During development you should be aware this might not work using ‘localhost’, depending on your OS. The best thing to do is to edit your hosts file to have “example.local” point to your machine and use those domains for testing instead.

If you’re doing anything more complicated, you’ve got your work cut out for you as you may need to write custom rack middleware (see: Google) and/or use a Proc. In the latest Rails, cookies are being handled by Rack (instead of CGI); in any version, setting Cookies via cookies[:key]= is performed independent of the session options which is why you must specify the domain separately. There are some folks who describe monkey patching Rails to set the domain automatically but this is unreliable as I believe it’s changed every release. If you don’t want to have to change it, just create a wrapper method for setting your cookies, or, set the domain wherever you set or delete a cookie. We only set one cookie via restful-authentication so 2 lines is a fairly simple fix.

restful-authentication + subdomain-fu = needing cookie adjustments