-
Notifications
You must be signed in to change notification settings - Fork 45
Sharing cookies among subdomains
Abraham edited this page Apr 19, 2017
·
3 revisions
This is a guide on how to configure Rails apps to share cookies among subdomains.
Sharing cookies it's very easy with Rails, however, there are a few things to consider.
- You need to checkout the Mozilla Foundation’s Public Suffix List. The reason is that companies like Heroku listed themselves so no cookie can be shared among subdomains. This means that for testing you cannot share cookies with domains like herokuapp. If you add a custom domain (and therefore subdomains) you are good to go.
- Verify your Rails version. Different version of Rails create different cookies. That means not only the process of creating cookies but also what type of serializer they use.
- Verify your secret key base. Depending on your Rails version you might have a secret_token.rb or secrets.yml. ALL the apps must have the same secret key base. This is because the secret key base is used for encryption.
-
Verify your key. In your
session_store.rb
,key
value MUST be the same in all your apps. Bear in mind that you need different key values for different environments. We doubt you want to share your cookies among environments, however, that's up to you. - Your domain in
session_store.rb
MUST be the domain, i.e.,ihavenoideawhatiamdoing.com
.
This is an example of session_store.rb
# In case you have many domains either for development or production
# We define all the subdomains in a environment variable.
session_domains = ENV.fetch('DOMAINS', 'defaultdomain.com').split(',').map(&:strip)
session_store_key = ENV.fetch('SESSION_KEY', "_example_#{Rails.env}")
App::Application.config.session_store :cookie_store,
key: session_store_key,
domain: session_domains
This is an example of cookies_serializer.rb
# Specify a serializer for the signed and encrypted cookie jars.
# Valid options are :json, :marshal, and :hybrid.
# Before Rails 4.1 all the cookies were serialized using Marshal library of Ruby. To prevent
# this Rails provides with a hybrid serializer. The hybrid serializer deserializes marshalled cookies and stores # them in JSON format for the next use. All the new cookies will be serialized in the JSON format.
App::Application.config.action_dispatch.cookies_serializer = :json
And basically that's everything you need! Something to remember: don't forget to delete your cookies in your browser(s) or you are going bonkers.