Login

Dry basic-auth middleware using Django's AUTHENTICATION_BACKENDS and "basicauth" lib

Author:
pakal
Posted:
June 13, 2019
Language:
Python
Version:
2.1
Tags:
middleware basic authentication auth http-authorization
Score:
0 (after 0 ratings)

Requires to install "basicauth" package, which does basic-auth header encoding/decoding cleanly according to RFCs.

Could be improved to return a "realm" in case of http401, like in https://djangosnippets.org/snippets/1720/, although I'm not sure it's really useful in django usecases.

 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
29
30
31
32
33
34
35
36
37
from django.contrib.auth import authenticate
from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin

import basicauth


class DjangoBasicAuthMiddleware(MiddlewareMixin):
    """
    This middleware should be placed AFTER the standard session-based
    AuthenticationMiddleware of Django, if this one is used.

    If request.user is missing or anonymous, this middleware attempts to authenticate
    the request using basic-auth headers, which must contain valid username/password
    credentials recognized by one of the AUTHENTICATION_BACKENDS of Django.
    """

    def process_request(self, request):

        if hasattr(request, "user") and request.user.is_authenticated:
            return  # Don't interfere with standard authentication

        basic_auth_header = request.META.get("HTTP_AUTHORIZATION")
        if not basic_auth_header:
            return

        try:
            username, password = basicauth.decode(basic_auth_header)
        except basicauth.DecodeError:
            pass  # Do not log sensitive data, just let it be

        user = authenticate(request=request, username=username, password=password)

        if not user:  # Help the client guess the problem, since it attempted basic-auth
            return HttpResponse("Invalid Basic Auth credentials", status=401)

        request.user = user  # Might override an AnonymousUser

More like this

Comments

Please login first before commenting.