Last active
November 14, 2016 08:36
-
-
Save coilysiren/ecc6ca903c928bb7ce46f180372f7925 to your computer and use it in GitHub Desktop.
django 1.10 basic auth (for the entire website)
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
# builtin | |
import base64 | |
# django | |
from django.http import HttpResponse | |
from django.conf import settings | |
def _unauthed(): | |
response = HttpResponse(''' | |
<html><title>Authorization required</title><body> | |
<h1>Authorization Required</h1></body></html> | |
''') | |
response['WWW-Authenticate'] = 'Basic realm=""' | |
response.status_code = 401 | |
return response | |
def _valid_login(auth): | |
username, password = base64.b64decode(auth).decode('utf-8').split(':', 1) | |
if not username == settings.BASICAUTH_USERNAME: | |
return False | |
if not password == settings.BASICAUTH_PASSWORD: | |
return False | |
return True | |
def basic_auth_middleware(get_response): | |
def middleware(request): | |
if not request.META.get('HTTP_AUTHORIZATION'): | |
return _unauthed() | |
else: | |
auth = request.META['HTTP_AUTHORIZATION'].split(' ',1) | |
if 'basic' != auth[0].lower(): | |
return _unauthed() | |
if _valid_login(auth[1]): | |
return get_response(request) | |
else: | |
return _unauthed() | |
return middleware |
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
BASICAUTH_USERNAME = 'XXXX' | |
BASICAUTH_PASSWORD = 'XXXX' | |
MIDDLEWARE.append( | |
'config.middleware.basic_auth_middleware', | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment