Created
December 30, 2013 13:33
-
-
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
This file contains 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
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