Skip to content

Instantly share code, notes, and snippets.

@ratpik
Created December 30, 2013 13:33
Show Gist options
  • Save ratpik/8182148 to your computer and use it in GitHub Desktop.
Save ratpik/8182148 to your computer and use it in GitHub Desktop.
Enable Basic Authetication in your django views. Useful when you have a ajax view accessed by a client that is csrf exempt on HTTP POST
import base64
from django.contrib.auth import authenticate
'''
In your views you can call has_basic_auth(request) to check if request headers have a valid Authorization header or not.
Returns False if header is absent or based on invalid username/password combination.
Handle the result in your view accordingly
Based on https://djangosnippets.org/snippets/243/
'''
def has_basic_auth(request):
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:
if user.is_active:
return True
return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment