Created
October 1, 2024 10:53
-
-
Save kontur/fc905f11933f5c9d0598ae5c3e2429cd to your computer and use it in GitHub Desktop.
Djanto Basic Auth to secure entire site with user/password protection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import base64 | |
from django.http import HttpResponse | |
from django.conf import settings | |
from django.utils.deprecation import MiddlewareMixin | |
class BasicAuthMiddleware(MiddlewareMixin): | |
""" | |
Adopted from https://www.djangosnippets.org/snippets/2468/ for Django 5.1 | |
Add yourapp.yourmodule.BasicAuthMiddleware to settings.py MIDDLEWARE | |
Add BASICAUTH_USERNAME and BASICAUTH_PASSWORD to your settings.py | |
""" | |
async_capable = False | |
async_mode = False | |
def __init__(self, get_response): | |
self.get_response = get_response | |
# One-time configuration and initialization. | |
def unauthed(self): | |
response = HttpResponse("<html><title>Auth required</title><body><h1>Authorization Required</h1></body></html>") | |
response["WWW-Authenticate"] = 'Basic realm="Development"' | |
response.status_code = 401 | |
return response | |
def process_request(self, request): | |
if "HTTP_AUTHORIZATION" not in request.META: | |
return self.unauthed() | |
else: | |
authentication = request.META["HTTP_AUTHORIZATION"] | |
(authmeth, auth) = authentication.split(" ", 1) | |
if "basic" != authmeth.lower(): | |
return self.unauthed() | |
try: | |
auth = base64.b64decode(auth.strip()).decode("utf-8") | |
username, password = auth.split(":", 1) | |
if ( | |
username == settings.BASICAUTH_USERNAME | |
and password == settings.BASICAUTH_PASSWORD | |
): | |
return None | |
except: | |
pass | |
return self.unauthed() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment