Technology for ponies

Mar 25, 2014

Use HTTP basic authentification to login into Django

Let's imagine you have a view somewhere on your website you want to password protect using your usual django login but you are too lazy to design a form to input your credentials. This makes sense if the view is for your own use and you don't need to have a fancy login page. In such a case the easiest and fastest way to proceed is to use the standard HTTP basic authentification to let your browser asks for your credentials.

It is then easy to get the user / password back in your view and to authenticate yourself into django. Here is the code snippet to do this :

from django.http import HttpResponse
from django.contrib.auth import authenticate
import base64

def my_view(request):
      if 'HTTP_AUTHORIZATION' in request.META:
              auth = request.META['HTTP_AUTHORIZATION'].split()
              if len(auth) == 2:
                      if auth[0].lower() == "basic":
                              username, password = base64.b64decode(auth[1]).split(':', 1)
                              user = authenticate(username=username, password=password)
                              if user is not None and user.is_staff:
                                      # handle your view here
                                      return render_to_response('my_template.html')

      # otherwise ask for authentification
      response = HttpResponse("")
      response.status_code = 401
      response['WWW-Authenticate'] = 'Basic realm="restricted area"'
      return response

If you need to protect more than one view you should wrap this code in a view decorator.

Please not that using HTTP basic authentification your username and password are sent base64 encoded but as it can be easily decoded you should have your website served over https to keep your crendentials secured.