[Django]-How to enable basic access authentication in django

5πŸ‘

βœ…

I can think of multiple ways to do this. If you want your entire django application protected by basic authentication then you can add an authentication middleware to your wsgi app. Django creates a default wsgi application in your project. Add the following middleware to this wsgi.py file:

class AuthenticationMiddleware(object):
def __init__(self, app, username, password):
    self.app = app
    self.username = username
    self.password = password
def __unauthorized(self, start_response):
    start_response('401 Unauthorized', [
        ('Content-type', 'text/plain'),
        ('WWW-Authenticate', 'Basic realm="restricted"')
    ])
    return ['You are unauthorized and forbidden to view this resource.']
def __call__(self, environ, start_response):
    authorization = environ.get('HTTP_AUTHORIZATION', None)
    if not authorization:
        return self.__unauthorized(start_response)

    (method, authentication) = authorization.split(' ', 1)
    if 'basic' != method.lower():
        return self.__unauthorized(start_response)

    request_username, request_password = authentication.strip().decode('base64').split(':', 1)
    if self.username == request_username and self.password == request_password:
        return self.app(environ, start_response)

    return self.__unauthorized(start_response)

Then, instead of calling
application = get_wsgi_application()
You should use:
application = AuthenticationMiddleware(application, "myusername", "mypassword")

This will ensure that every request to your django server goes through basic authentication.
Please note that unless you’re using HTTPS then basic authentication isn’t secure and the user credentials will not be encrypted.

If you only want some of your views to be covered by basic authentication then you can modify the above class to be a function decorator :

def basic_auth_required(func):
    @wraps(func)
    def _decorator(request, *args, **kwargs):
        from django.contrib.auth import authenticate, login
        if request.META.has_key('HTTP_AUTHORIZATION'):
            authmeth, auth = request.META['HTTP_AUTHORIZATION'].split(' ', 1)
            if authmeth.lower() == 'basic':
                auth = auth.strip().decode('base64')
                username, password = auth.split(':', 1)
                if username=='myusername' and password == 'my password':
                    return func(request, *args, **kwargs)
                else:
                    return HttpResponseForbidden('<h1>Forbidden</h1>')
        res = HttpResponse()
        res.status_code = 401
        res['WWW-Authenticate'] = 'Basic'
        return res
    return _decorator

Then you can decorate your views with this to activate basic authentication.

Note that the username/password are both hardcoded in the examples above. You can replace that with your own mechanism.

Hope this helps

πŸ‘€elynch

-1πŸ‘

As mentioned in the docs, the REMOTE_USER is set by the web server. Typically you will need to configure a web server like Apache or IIS to protect a site or a directory using HTTP Basic Authentication.

For debug purposes, I suggest setting a dummy user in the manage.py, say:

import os
from django.conf import settings

if settings.DEBUG:
    os.environ['REMOTE_USER'] = "terry"
πŸ‘€arocks

Leave a comment