Adding dynamic TLD to session cookies to enable subdomain usage

69 views
Skip to first unread message

Alex Wolkov

unread,
May 6, 2016, 7:06:44 PM5/6/16
to Django developers (Contributions to Django itself)
Hi All, 

First post here, please redirect me where needed if is not appropriate. 

I wanted to suggest a feature. 

Our current plan is to use the same Django on subdomain.domain.com and domain.org, and a different Django with CMS on the TLD domain.com

We want to enable cookie saving with the TLD so that subdomains will be able to see that cookie, but using SESSION_COOKIE_DOMAIN breaks the 2 domains set up. 

My suggestion is adding a settings config with something like settings.SESSION_ENABLE_SUBDOMAIN

This in turn will trigger a behavior in django.contrib.sessions.middleware that will extract the TLD from the current domain, attach a . to it and save the session on that TLD.

Does this make sense to anyone? Or am I missing a really obvious way of achieving this?

Would love to hear your thoughts.


P.S - proposed code for the TLD extraction will look something like this :

    def _get_cookie_domain(self, request):
        """
        Overriding the session cookie domain here instead of settings,
        It lets us write a session cookie to .domain.com and have the session be cross domain
        Using this in request context works even if we have several domains hosted on the same Django
        :param request:
        :return:
        """
        host = request.META.get('HTTP_HOST')
        if settings.SESSION_ENABLE_SUBDOMAIN and host in settings.ALLOWED_HOSTS:
            cookie_domain =  '.'.join(host.split('.')[-2:])
        else:
            cookie_domain = None
        return cookie_domain


Reply all
Reply to author
Forward
0 new messages