Hello, forgive me if I am posting a repeat topic, but I have not found this anywhere.
I am developing a django-rest-framework application that will eventually live on a server with it’s own authentication provider that will set the REMOTE_USER server variable. However, it is unlikely that I will be able to get this authentication provider working on my computer’s localhost server, so I am wondering if there are any clever ways to ‘spoof’ a remote_user variable for local development and testing purposes.
So far I have tried using decorators and a local proxy to no avail.
Thanks!
I love questions like this! Seriously! This gives me a chance to dig into some areas of Django that I wouldn’t ordinarily see.
So, what I’ve found from this is that while it may be possible to override or monkey-patch enough of runserver to do this, it doesn’t seem to me to be the easiest way to handle this.
What I found is that I could create a wrapper around the wsgi application object such that this works with either Werkzeug (using runserver_plus
) or Gunicorn.
My wsgi.py
file now looks like this:
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dt.settings')
django_app = get_wsgi_application()
def application(environ, start_response):
environ['REMOTE_USER'] = "somebody"
return django_app(environ, start_response)
1 Like
Hey, thanks for the reply!
Since my first post, I’ve gone with this solution that I’ve gotten working locally. I have not tested on the server.
Your version may be better, I’m open to discussion!
from django.contrib.auth.backends import RemoteUserBackend
from django.conf import settings
class SpoofedUser:
def __init__(self, username):
self.username = username
self.is_active = True
self.is_authenticated = True
class LocalRemoteUserAuthBackend(RemoteUserBackend):
def authenticate(self, request, **kwargs):
# Check if the environment variable is set to enable spoofed usernames
if settings.ENVIRONMENT == 'local':
spoofed_username = <username>
return SpoofedUser(spoofed_username)
else:
return super().authenticate(request, **kwargs)