Login

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

Author:
pakal
Posted:
June 13, 2019
Language:
Python
Version:
2.1
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

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

Comments

Please login first before commenting.