Skip to content

Instantly share code, notes, and snippets.

@nicksnell
Created November 1, 2013 13:09
Show Gist options
  • Select an option

  • Save nicksnell/7265184 to your computer and use it in GitHub Desktop.

Select an option

Save nicksnell/7265184 to your computer and use it in GitHub Desktop.
Dead simple HTTP Auth decorator for django. Just add @http_basic_auth(username='...some user...', password='...some pass...') round the view
from django.http import HttpResponse, HttpResponseForbidden
def _auth_request(realm):
response = HttpResponse()
response.status_code = 401
response['WWW-Authenticate'] = 'Basic realm="%s"' % realm
return response
def http_basic_auth(username=None, password=None, realm='Authorization required'):
"""HTTP Basic Auth for a view"""
def wrapper(fn, *args, **kwargs):
def _decorator(request, *args, **kwargs):
if not request.META.has_key('HTTP_AUTHORIZATION'):
return _auth_request(realm)
authmeth, auth = request.META['HTTP_AUTHORIZATION'].split(' ', 1)
if authmeth.lower() == 'basic':
auth = auth.strip().decode('base64')
auth_username, auth_password = auth.split(':', 1)
if (username == auth_username and password == auth_password):
return fn(request, *args, **kwargs)
return _auth_request(realm)
return _decorator
return wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment