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
- Template tag - list punctuation for a list of items by shapiromatron 11 months ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 1 week ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.