A very basic Basic Auth middleware that uses a username/password defined in your settings.py as BASICAUTH_USERNAME
and BASICAUTH_PASSWORD
. Does not use Django auth. Handy for quickly securing an entire site during development, for example.
In settings.py:
BASICAUTH_USERNAME = 'user'
BASICAUTH_PASSWORD = 'pass'
MIDDLEWARE_CLASSES = (
'app.module.BasicAuthMiddleware',
#all other middleware
)
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 | from django.http import HttpResponse
from django.conf import settings
class BasicAuthMiddleware(object):
def unauthed(self):
response = HttpResponse("""<html><title>Auth required</title><body>
<h1>Authorization Required</h1></body></html>""", mimetype="text/html")
response['WWW-Authenticate'] = 'Basic realm="Development"'
response.status_code = 401
return response
def process_request(self,request):
if not request.META.has_key('HTTP_AUTHORIZATION'):
return self.unauthed()
else:
authentication = request.META['HTTP_AUTHORIZATION']
(authmeth, auth) = authentication.split(' ',1)
if 'basic' != authmeth.lower():
return self.unauthed()
auth = auth.strip().decode('base64')
username, password = auth.split(':',1)
if username == settings.BASICAUTH_USERNAME and password == settings.BASICAUTH_PASSWORD:
return None
return self.unauthed()
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks 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, 7 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Where does i need to add 28 lines of code, could you please help?
#
Still mostly works, here's one that's python 3 friendly:
``` import base64
from django.core.exceptions import MiddlewareNotUsed from django.http import HttpResponse from django.conf import settings
AUTH_TEMPLATE = """
<html> <title>Authentication Required</title> <body> Sorry, we're not ready for you yet. </body> </html>"""
class BasicAuthMiddleware(object): def init(self, get_response): self.get_response = get_response
```
#
as @bugwrangler mentioned, could anyone give a bit more details how to use above 28 lines of code? e.g which file.py and where? and any requirements to urls.py or else and loading sequence?
I have put those into root( e.g. mysite\views.py on top of every other class of def, but the login window still not shown up. PS: does it need to restart Django? e.g. python ./manage.py runserver 0:8080?
thanks!
#
Please login first before commenting.