Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing django sessions on specific subdomains

I have example.com and support.example.com . If a user is logged in on the main site, I'd like to have the session be accessible from the support site.

Setting the SESSION_COOKIE_DOMAIN to '.example.com' isn't what I want because I have many, many other subdomains with django apps that I would like to NOT have access to the session.

Currently my only conceivable workaround involves tricky redirects, which I'd like to avoid if necessary.

Is there any way to do this?

like image 820
dave paola Avatar asked Sep 18 '10 17:09

dave paola


4 Answers

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.

like image 135
Florian Ledermann Avatar answered Nov 13 '22 02:11

Florian Ledermann


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).

like image 6
Carles Barrobés Avatar answered Nov 13 '22 03:11

Carles Barrobés


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.

like image 2
Sam Dolan Avatar answered Nov 13 '22 01:11

Sam Dolan


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.

like image 1
Dhasthagheer Avatar answered Nov 13 '22 01:11

Dhasthagheer