Login

Basic Auth Middleware

Author:
joshsharp
Posted:
June 22, 2011
Language:
Python
Version:
1.3
Score:
2 (after 4 ratings)

A very basic Basic Auth middleware that uses a username/password defined in your settings.py as BASICAUTH_USERNAME and BASICAUTH_PASSWORD. Does not use Django auth. Handy for quickly securing an entire site during development, for example.

In settings.py:

BASICAUTH_USERNAME = 'user'
BASICAUTH_PASSWORD = 'pass'

MIDDLEWARE_CLASSES = (
    'app.module.BasicAuthMiddleware',
    #all other middleware
)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from django.http import HttpResponse
from django.conf import settings

class BasicAuthMiddleware(object):
    
    
    def unauthed(self):
        response = HttpResponse("""<html><title>Auth required</title><body>
                                <h1>Authorization Required</h1></body></html>""", mimetype="text/html")
        response['WWW-Authenticate'] = 'Basic realm="Development"'
        response.status_code = 401
        return response
    
    def process_request(self,request):
        if not request.META.has_key('HTTP_AUTHORIZATION'):
            
            return self.unauthed()
        else:
            authentication = request.META['HTTP_AUTHORIZATION']
            (authmeth, auth) = authentication.split(' ',1)
            if 'basic' != authmeth.lower():
                return self.unauthed()
            auth = auth.strip().decode('base64')
            username, password = auth.split(':',1)
            if username == settings.BASICAUTH_USERNAME and password == settings.BASICAUTH_PASSWORD:
                return None
            
            return self.unauthed()

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

bugwrangler (on June 1, 2015):

Where does i need to add 28 lines of code, could you please help?

#

umbrae (on March 19, 2017):

Still mostly works, here's one that's python 3 friendly:

``` import base64

from django.core.exceptions import MiddlewareNotUsed from django.http import HttpResponse from django.conf import settings

AUTH_TEMPLATE = """

<html> <title>Authentication Required</title> <body> Sorry, we're not ready for you yet. </body> </html>

"""

class BasicAuthMiddleware(object): def init(self, get_response): self.get_response = get_response

    # If DEBUG is true, we're in dev. Raise MiddlewareNotUsed to remove
    # this middleware from the list.
    # TODO: This should probably be based off of the QA env once we hit
    # production
    if settings.DEBUG:
        raise MiddlewareNotUsed

def _unauthed(self):
    response = HttpResponse(AUTH_TEMPLATE, content_type="text/html")
    response['WWW-Authenticate'] = 'Basic realm="Development"'
    response.status_code = 401
    return response

def __call__(self, request):
    if 'HTTP_AUTHORIZATION' not in request.META:
        return self._unauthed()
    else:
        authentication = request.META['HTTP_AUTHORIZATION']
        (auth_method, auth) = authentication.split(' ', 1)
        if 'basic' != auth_method.lower():
            return self._unauthed()
        auth = base64.b64decode(auth.strip()).decode('utf-8')
        username, password = auth.split(':', 1)
        if (
            username == settings.BASICAUTH_USERNAME and
            password == settings.BASICAUTH_PASSWORD
        ):
            return self.get_response(request)

        return self._unauthed()

```

#

Gustaf88 (on September 7, 2021):

as @bugwrangler mentioned, could anyone give a bit more details how to use above 28 lines of code? e.g which file.py and where? and any requirements to urls.py or else and loading sequence?

I have put those into root( e.g. mysite\views.py on top of every other class of def, but the login window still not shown up. PS: does it need to restart Django? e.g. python ./manage.py runserver 0:8080?

thanks!

#

Please login first before commenting.