About Django View with Basic Authentication

You can implement Basic authentication directly in a Django view, as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import base64
from django.shortcuts import render
from django.http import HttpResponse
from django.utils.encoding import force_str

def secret_page(request):
    authorization_passed = False
    if "HTTP_AUTHORIZATION" in request.META:
        auth = request.META["HTTP_AUTHORIZATION"].split()
        if len(auth) == 2:
            if auth[0].lower() == "basic":
                username, password = (
                    force_str(base64.b64decode(auth[1])).split(":")
                )
                if username == "demo" and password == "demo":
                    authorization_passed = True

    if not authorization_passed:
        response = HttpResponse()
        response.status_code = 401
        response["WWW-Authenticate"] = 'Basic realm="Django Website"'
        return response

    return render(request, "pages/secret_page.html")

Tips and Tricks Programming Development Security Django 5.x Django 4.2 Django 3.2