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
- Require Login Middleware by mattgrayson 4 years, 5 months ago
- ad-hoc request authentication by mwicat 2 years ago
- HTTP (basic) auth enabled (new-style) syndication framework feed class by hupf 2 years, 5 months ago
- view by view basic authentication decorator by Scanner 6 years ago
- Login Required Middleware with Next Parameter by bernardoporto 6 months ago
Comments
?? 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?
#
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.
#