Question

I have a Rails app that sets a cookie and does a redirect to another server once the user is logged in. However, the cookie that the Rails app sets isn't seen by the server for some reason. I've tried setting http_only to false but I still can't even see the cookie unless the domain is the same as my Rails app. Here's the code I'm using to set the cookie:

cookies[:dev_appserver_login] = 
  { :value => "#{email}:#{nick}:#{admin}:#{hsh}",
    :domain => "webserver-to-redirect-to",
    :expires => 30.days.from_now }

redirect_to session[:dest_url]

If I manually create a cookie with the Web Developer extension in Firefox it works fine, but not when Rails does it. Any ideas?

Was it helpful?

Solution

What are the redirecting and redirected-to servers? You can only set ‘domain’ to the current hostname or a parent domain, so if you're on a.example.com and you're redirecting to b.example.com, you have to set ‘domain’ to .example.com, not b.example.com as implied in the code snippet.

(And open domains like the .com TLD aren't themselves allowed as domain values, so if you want to pass a cookie from a.example.com to b.somewhereelse.com you will need a more complicated solution probably involving changing the code on somewhereelse.com.)

OTHER TIPS

I still can't even see the cookie unless the domain is the same as my Rails app.

That's how cookies are supposed to work. If you're accessing it directly by IP, then as far as the web browser is concerned, your 'domain' is just your IP, so the same rules apply.

You can get around this in development mode by editing your /etc/hosts file and creating host names for your apps

127.0.0.1 app1.localdev.com, app2.localdev.com

Then, when the cookie is created set the domain to '.localdev.com' (note the preceeding period') which will allow any app at any subdomain of localdev.com to read it.

Another broader solution (which is better for production deploys, but more work to set up) is to set up a path proxy for the sub-app so requests to appdomain.com go to app1 and requests to appdomain.com/other-app/ are proxied to the other app. This lets them share the root domain and easily share cookies.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top