Skip to content

Instantly share code, notes, and snippets.

@codeinthehole
Created February 7, 2013 16:39
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save codeinthehole/4732233 to your computer and use it in GitHub Desktop.
Save codeinthehole/4732233 to your computer and use it in GitHub Desktop.
Basic auth for Django snippet
import base64
from django.http import HttpResponse
from django.contrib.auth import authenticate
from django.conf import settings
def view_or_basicauth(view, request, *args, **kwargs):
# Check for valid basic auth header
if 'HTTP_AUTHORIZATION' in request.META:
auth = request.META['HTTP_AUTHORIZATION'].split()
if len(auth) == 2:
if auth[0].lower() == "basic":
uname, passwd = base64.b64decode(auth[1]).split(':')
user = authenticate(username=uname, password=passwd)
if user is not None and user.is_active:
request.user = user
return view(request, *args, **kwargs)
# Either they did not provide an authorization header or
# something in the authorization attempt failed. Send a 401
# back to them to ask them to authenticate.
response = HttpResponse()
response.status_code = 401
response['WWW-Authenticate'] = 'Basic realm="%s"' % settings.BASIC_AUTH_REALM
return response
def basicauth(view_func):
def wrapper(request, *args, **kwargs):
return view_or_basicauth(view_func, request, *args, **kwargs)
return wrapper(tws)
@AbsolutRed
Copy link

Hi,

A decode('utf-8') needs to follow b64decode() before using the split() function for strings:
uname,passwd = base64.b64decode(auth[1]).decode('utf-8').split(':')

@armut
Copy link

armut commented Dec 1, 2016

What is "tws" here in the last line "return wrapper(tws)" ?

@benekastah
Copy link

That last function might be better like this:

def basicauth(view_func):
    def wrapper(request, *args, **kwargs):
        return view_or_basicauth(view_func, request, *args, **kwargs)
    wrapper.__name__ = view_func.__name__
    return wrapper

@nemish
Copy link

nemish commented Sep 19, 2017

Or even better

from functools import wraps
def basicauth(view_func):
    @wraps(view_func)
    def wrapper(request, *args, **kwargs):
        return view_or_basicauth(view_func, request, *args, **kwargs)
    return wrapper

@gregsadetsky
Copy link

note that for python 3, you will have to do

user = authenticate(
    username=uname.decode("utf-8"),
    password=passwd.decode("utf-8"),
)

otherwise the (not decoded, i.e. bytes) values of uname and passwd won't be accepted in the authenticate call (i.e. they won't match any user!)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment