[Django]-Sharing django sessions on specific subdomains

36👍

The solution would be to set

SESSION_COOKIE_DOMAIN = '.example.com'

and rename the session cookie name, e.g.

SESSION_COOKIE_NAME = 'examplesessionid'

on the Django instance that is driving the two subdomains. The two sites will use the renamed cookie with a global scope and not interfere with the other Django instances, using the default ‘sessionid’ cookie on their respective subdomains.

Note that the cookie will be sent to the other Django instances on subdomains of example.com, but will not be interpreted as a Django session cookie.

6👍

I recently saw a similar question in:
How to get distinct Django apps on same subdomain to share session cookie?

Where it was recommended to have separate sessions but a single-sign-on using django-cas (you only login to one of the sites).

2👍

You could write your own SessionMiddleware to set and retrieve the cookies based on domains.

Basically you’d want to copy the existing SessionMiddleware class. In the process_request function to look at the domain and retrieve the correct cookie to setup the SessionStore. In the process_response you’ll want to write the cookies for both sub domains. In your settings you’ll delete the existing SessionMiddleware class and replace it with your own.

This is just off the top of my head, so don’t hate me if it doesn’t work. Best of luck, and please post your findings for future readers.

1👍

Following value should be same in all your django applications

SESSION_COOKIE_DOMAIN = ".example.com"

SESSION_COOKIE_NAME = "anycookiename"

SECRET_KEY="anykey" 

If you are using memcached, set same memcached location in all your django applications.

0👍

I dont know django, but is possible for you to set 2 cookies instead of 1? See, a cookie is send only if cookie domain matches url domain correct? If you want to have the same session on 2 different domains you could set 2 cookies with same value and diferent domains. In this case .example.com and support.example.com. So you will receive this cookie only when acessing one of those.

0👍

I’ve got app with multiple domains, so solution with changing something in settings.py wasn’t good for me. So i set cookie for main domain like that:

# let's get our domain
arr = request.get_host().split(':')[0].split('.')
# if we are at subdomain page right now
# we should delete subdomain using:
# arr.pop(0)
domain = ".".join(arr)
response.set_cookie('city', 'somevalue, domain="."+domain)

This code set cookie for all subdomains from domain/sudomain pages.

Leave a comment