Login

HTTP basic auth decorator

Author:
bthomas
Posted:
February 2, 2009
Language:
Python
Version:
1.0
Score:
0 (after 0 ratings)

This is a somewhat simpler alternative to http://www.djangosnippets.org/snippets/243/ that does not return a 401 response. It's meant to be used along with the login_required decorator as an alternative way to authenticate to REST-enabled views.

Usage:

@http_basic_auth
@login_required
def my_view(request):
    ...

If an HTTP basic auth header is provided, the request will be authenticated before the login_required check happens. Otherwise, the normal redirect to login page occurs.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
from functools import wraps

def http_basic_auth(func):
    @wraps(func)
    def _decorator(request, *args, **kwargs):
        from django.contrib.auth import authenticate, login
        if request.META.has_key('HTTP_AUTHORIZATION'):
            authmeth, auth = request.META['HTTP_AUTHORIZATION'].split(' ', 1)
            if authmeth.lower() == 'basic':
                auth = auth.strip().decode('base64')
                username, password = auth.split(':', 1)
                user = authenticate(username=username, password=password)
                if user:
                    login(request, user)
        return func(request, *args, **kwargs)
    return _decorator

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 8 months ago

Comments

peterbe (on February 2, 2009):

?? So if you fail the basic auth popup, it redirects to the web based login? How are REST apps going to like that?

What's wrong with snippet 243?

#

bthomas (on February 5, 2009):

Snippet 243 should definitely be used for REST-only views, there's nothing wrong with it.

The views I am applying this to will be mainly serving HTML to users, and XML/JSON to REST apps if they request it. I don't want normal users getting a 401 (and browser requesting credentials) if they navigate to a page while not logged in. REST apps probably won't like the redirect either, but I'm just more concerned about the experience for humans in this case.

#

babbbrak_poradny (on November 7, 2013):

If there is no such entry: request.META['HTTP_AUTHORIZATION'] and you use Django on Apache, READ THIS: http://stackoverflow.com/questions/13387516/authorization-header-missing-in-django-rest-framework-is-apache-to-blame Apache in default deletes HTTP_AUTHORIZATION header for CGI.

#

Please login first before commenting.