Search code examples
ruby-on-railsrubycookies

How to get a cookie form a specific subdomain with Ruby on Rails


In Ruby on Rails, you can delete and set cookies with options in a hash, such as :domain that you could change to sub.domain.com instead of .domain.com to get some control of your subdomain cookies.

I'm working on a SPA that set cookies from the front-end and the domain it's set on is app.domain.com and it'd be kind of tricky to change the mechanism here. The Rails app needs to read one of the cookies on .domain.com so, of course, it returns nil

Is there any way in Rails to get the value of a cookie from a subdomain? I've looked throughout the documentation and public methods from cookies itself and couldn't find anything useful.


Solution

  • No, that is not possible without changing how the cookie is set.

    When setting a cookie without explicitly setting a domain, then the browser will only send the cookie to the exact same domain, not even to subdomains of that domain. This is a security feature implemented in the browser and, of course, the application has no way to access cookies that are not sent by the browser with the request to the server.

    When setting a cookie with an explicit domain (for example sub.domain.com), then the cookie will be shared with that domain and all subdomains of that domain (like foo.sub.domain.com). But it is still not shared with the parent domain.

    The only way to make it work, would be to set the cookie explicitly to domain.com which would tell the browser to share this cookie with domain.com, but also with all subdomains, like sub.domain.com, foo.sub.domain.com, or sub2.domain.com.

    Note: Sharing the cookie across all subdomains can have serious security implications depending on what your cookie is used for – especially when some of your subdomains are not fully controlled by yourselves, but by third parties. For example, if you shared a session token that way and had a third party SaaS product configured to use one of your subdomains, then the session token would be shared with that third party tool.