views:

159

answers:

2

Hi,

I'm trying to set a cookie in one domain and access it from another. Is this possible?

Here's what I'm doing in my app:

In a controller, the test action is accessed via this url:

http://myapp.com/account/test

def test
  cookies[:foo] = {
    :value => 'something',
    :domain => 'myapp.heroku.com'
  }
end

In same controller, the test2 action is accessed via this url:

http://myapp.heroku.com/account/test2

def test2 
  puts "foo=#{cookies[:foo]}"
end

but the value of cookies[:foo] is always blank. Is it possible to access the cookie from the heroku.com domain. I thought setting the :domain option would allow this.

Thanks.

+2  A: 

You can't do this for a different domain, but you can do it for subdomains. So, for instance, an app running on domain example.com can set a cookie for subdomain.example.com but not for exampleapp.com.

I have to add, if it were possible to set cookies for other, arbitrary domains, there would be massive security/privacy issues.

You can set the same cookies for all your domains by doing the following in environment.rb:

 ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS[:session_domain => '.mydomain.com']

see here for the documentation.

Ron Gejman
Also, it's possible that some browsers (or plugins) won't let your app do this... but I don't know for sure.
Ron Gejman
A: 

The :domain option (and setting domain on cookies in general) only really works across subdomains. i.e. for app1.mysite.com and app2.mysite.com - you could set the cookie domain to .mysite.com and have it shared between the sub-domains.

This is just how cookies are designed to work. myapp.com and myapp.heroku.com are separate domains, not sub-domains, so attempting to set the domain this way isn't going to work.

There are some ways to achieve true cross-domain cookies - but they are rather involved.

Nate