Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share session between two django application?

I have two django application which are on same server on port 80 and 9002. i.e. urls are www.abc.com and www.abc.com:9002 Both share same database postgresql for authentication. I want to share the share the session data between them so that user logged in to one application can log in automatically in another application.

I read these answers : Multiple Django apps, shared authentication and How to get distinct Django apps on same subdomain to share session cookie?

And did this in my both django application:

  1. Used the same secret key in both.
  2. Added these lines:

    SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies' SESSION_COOKIE_NAME = 'abc'
    SESSION_COOKIE_DOMAIN = '.abc.com'

But still I am unable to achieve the purpose. How to share the session cookie between two django apps so that i can have shared authentication?

like image 586
Manish Gupta Avatar asked Mar 29 '16 09:03

Manish Gupta


1 Answers

Other than you have to apply these settings to both applications, the only thing missing with your approach is the SESSION_COOKIE_DOMAIN.

You set it to '.abc.com', which means it will work if your app has domain name: www.abc.com and somesubdomain.abc.com.

But your second app in this case www.abc.com:9002, by including the port it doesn't share the same TLD with www.abc.com. So, django thinks www.abc.com:9002 and www.abc.com are very different domain and not from the same root .abc.com.

If I'm working on this, there are several possible approach:

  1. Combine both app into one single root django app. Django app were modular anyway, so you could create one single ROOT_URL_CONF and DJANGO_SETTINGS_MODULE to specify how these two apps works in the same domain. You could, for example, append a different prefix url for each app.

  2. You use load balancer, or reverse proxy, such as nginx or haproxy to assign different subdomain for each app, then deploy each app in a different port. Let's say, the end result is you have the first django app deployed on first.abc.com and the second app in second.abc.com (All with port 80 in the frontend), then it will share the same session. Just remember that in the backend you need to assign the actual port that the app uses.

Additional notes from mine. In production settings, you also want to add ALLOWED_HOSTS settings and include .abc.com in the list.

like image 64
lucernae Avatar answered Sep 20 '22 23:09

lucernae