[Django]-How to make multiple django websites share one user database to authenticate?

4πŸ‘

The Django docs cover having multiple database configured here, using the same β€˜auth_db’ and AuthRouter in multiple projects should work:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    },
    'auth_db': {
        'NAME': 'auth_db',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'mysql_user',
        'HOST': '127.0.0.1',
        'PASSWORD': 'swordfish',
    },

}


class AuthRouter(object):
    """
    A router to control all database operations on models in the
    auth application.
    """
    def db_for_read(self, model, **hints):
        """
        Attempts to read auth models go to auth_db.
        """
        if model._meta.app_label == 'auth':
            return 'auth_db'
        return None

    def db_for_write(self, model, **hints):
        """
        Attempts to write auth models go to auth_db.
        """
        if model._meta.app_label == 'auth':
            return 'auth_db'
        return None

    def allow_relation(self, obj1, obj2, **hints):
        """
        Allow relations if a model in the auth app is involved.
        """
        if obj1._meta.app_label == 'auth' or \
           obj2._meta.app_label == 'auth':
           return True
        return None

    def allow_migrate(self, db, model):
        """
        Make sure the auth app only appears in the 'auth_db'
        database.
        """
        if db == 'auth_db':
            return model._meta.app_label == 'auth'
        elif model._meta.app_label == 'auth':
            return False
        return None

4πŸ‘

The easiest way to do this, is just like how StackExchange does it; by creating your own openid provider.

Its very easy with python-openid, which provides a sample server as part of its documentation.

Once you have it setup, use django-social-auth to integrate with openid.

πŸ‘€Burhan Khalid

0πŸ‘

Here is an alternative solution without using the same DB as auth-db.

This procedure is based on CAS (Central Authentication Service) protocol which supports SSO (Single Sign-On) and SLO (Single Logout) for Django and Flask frameworks:

  1. A CAS-Client is needed so I used the new generation of Django-CAS called django-cas-ng package and here is its configuration to make your own client. (Also, here is a pre-configured client repo)
  2. A CAS-Server is needed so I used a pre-configured repo.

[NOTE]:

  • It supports Django 1.11, 2.x, and 3.x

Leave a comment