Skip to content Skip to sidebar Skip to footer

Django Send Authenticated User To Another Django Server With The Same Db

I know question sounds strange, I will explain it here. I have two Django servers which share the same DB. One is a light front/back server and the order one takes the heavy comput

Solution 1:

Have a look at REMOTE_USER authentication:

This document describes how to make use of external authentication sources (where the Web server sets the REMOTE_USER environment variable) in your Django applications. This type of authentication solution is typically seen on intranet sites, with single sign-on solutions such as IIS and Integrated Windows Authentication or Apache and mod_authnz_ldap, CAS, Cosign, WebAuth, mod_auth_sspi, etc.

Basically your "light" server does the authentication as it already does. When you are doing a request to your "heavy" server, you should set a Auth-User header containing the username of your user. Django will then automatically authenticates the corresponding user.

By default, Django will read an environment variable set by an authentication server. But we can make it work with a HTTP header instead:

# middlewares.pyfrom django.contrib.auth.middleware import RemoteUserMiddleware

classCustomHeaderMiddleware(RemoteUserMiddleware):
    header = 'HTTP_AUTH_USER'
# settings.py

MIDDLEWARE = [
    '...',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'my_project.middlewares.CustomHeaderMiddleware',
    '...',
]

Then, you can do something like this then in your request (assuming you have your Django user at hand):

s = requests.Session()

r1 = s.get(upload_process_url)
a = s.post(
    upload_process_url,
    files=request.FILES,
    headers={
        'Auth-User': user.username,
    },
)

Since you're not doing a request from a browser, you can avoid the CSRF protection by marking the called "heavy" view with @csrf_exempt decorator (as you found yourself).

Be careful though that your "heavy" server should not be accessible directly on the internet and always behind a proxy/VPN accessible only by your "light" server.

Post a Comment for "Django Send Authenticated User To Another Django Server With The Same Db"